Skip to content

Commit

Permalink
🧪 fix borked tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lachlanshoesmith committed Dec 15, 2024
1 parent 49f7dbb commit f3578b4
Show file tree
Hide file tree
Showing 3 changed files with 164 additions and 132 deletions.
22 changes: 18 additions & 4 deletions backend/src/config/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,24 @@ if (process.env['NODE_ENV'] !== 'test' && !STORAGE_URL) {
if (process.env['NODE_ENV'] !== 'test' && !SERVICE_KEY) {
throw new Error('Service key not found.');
}
const storageClient = new StorageClient(STORAGE_URL, {
apikey: SERVICE_KEY,
Authorization: `Bearer ${SERVICE_KEY}`,
});

export let storageClient: StorageClient | null = null;
if (STORAGE_URL && SERVICE_KEY) {
storageClient = new StorageClient(STORAGE_URL, {
apikey: SERVICE_KEY,
Authorization: `Bearer ${SERVICE_KEY}`,
});
}

export const uploadFile = async (
file: string,
fileType: string,
societyId: number,
eventName: string
) => {
if (!storageClient) {
throw new Error('Storage client not initialised.');
}
const { data, error } = await storageClient
.from('images')
.upload(
Expand All @@ -39,6 +46,9 @@ export const uploadFile = async (
};

export const getFile = async (path: string) => {
if (!storageClient) {
throw new Error('Storage client not initialised.');
}
const { data, error } = await storageClient.from('images').download(path);
if (error) {
throw new Error(error.message);
Expand All @@ -48,6 +58,10 @@ export const getFile = async (path: string) => {
};

export const getFileUrl = async (path: string) => {
if (!storageClient) {
throw new Error('Storage client not initialised.');
}

const { data } = await storageClient.from('images').getPublicUrl(path);

return data;
Expand Down
95 changes: 54 additions & 41 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ import { verifyOTP } from './routes/OTP/verifyOTP';
import {
findUserFromId,
updateUserPasswordFromEmail,
} from "./routes/User/user";
import { getFile, getFileUrl, uploadFile } from "./config/storage";
} from './routes/User/user';
import {
getFile,
getFileUrl,
storageClient,
uploadFile,
} from './config/storage';

declare module 'express-session' {
interface SessionData {
Expand Down Expand Up @@ -632,22 +637,25 @@ app.post(
//console.log(event);

// upload image to storage and get link
let imagePath;
let imagePath = '';
try {
if(Object.keys(event.banner).length > 0) {
if (event.banner && storageClient) {
const metaData = event.banner.metaData;
const base64Data = event.banner.buffer.split(',')[1];
if(base64Data) {
imagePath = await uploadFile(base64Data, metaData.type, event.societyId, event.name);
if (base64Data) {
imagePath = await uploadFile(
base64Data,
metaData.type,
event.societyId,
event.name
);
} else {
throw new Error("Invalid base64 string.");
throw new Error('Invalid base64 string.');
}
} else {
throw new Error("No banner submitted.");
}
} catch (error) {
return res.status(400).json({ message: `Unable to upload image.` });
};
}

try {
const eventRes = await prisma.event.create({
Expand Down Expand Up @@ -702,23 +710,26 @@ app.put('/event', async (req: TypedRequest<UpdateEventBody>, res: Response) => {
// upload image to storage and get link
let imagePath;
try {
if(Object.keys(event.banner).length > 0) {
if (Object.keys(event.banner).length > 0) {
const base64Data = req.body.banner.buffer.split(',')[1];
if(base64Data) {
if (base64Data) {
const metaData = req.body.banner.metaData;

imagePath = await uploadFile(base64Data, metaData
.type, event.societyId, event.name);
imagePath = await uploadFile(
base64Data,
metaData.type,
event.societyId,
event.name
);
} else {
throw new Error("Invalid base64 string.");
throw new Error('Invalid base64 string.');
}
} else {
throw new Error("No banner submitted.");
throw new Error('No banner submitted.');
}
} catch (error) {
return res.status(400).json({ error: (error as Error).message });
};

}

try {
const eventRes = await prisma.event.update({
Expand All @@ -740,9 +751,9 @@ app.put('/event', async (req: TypedRequest<UpdateEventBody>, res: Response) => {
imageFile = await getFileUrl(event.banner); // getFile(event.banner) if we wanted raw file
} catch (error) {
return res.status(400).json({ error: (error as Error).message });
};
}

return res.status(200).json({...event, banner: imageFile});
return res.status(200).json({ ...event, banner: imageFile });
} catch (e) {
return res.status(400).json({ message: 'Invalid event input' });
}
Expand Down Expand Up @@ -1228,16 +1239,16 @@ app.get('/user/keywords', async (req, res: Response) => {

const userID = sessionFromDB.userId;

let userKeywords = await prisma.user.findFirst({
where: {
id: userID,
},
select: {
keywords: true,
}
});
if (userKeywords === null) return res.status(404).json([]);
let userKeywords = await prisma.user.findFirst({
where: {
id: userID,
},
select: {
keywords: true,
},
});

if (userKeywords === null) return res.status(404).json([]);

return res.status(200).json(userKeywords.keywords);
});
Expand Down Expand Up @@ -1277,21 +1288,21 @@ app.post(
});
return res.status(200).json(newKeyword);
} catch (e) {
return res.status(400).json({ message: "Invalid keyword input." });
return res.status(400).json({ message: 'Invalid keyword input.' });
}
}
);

// associates a user with a keyword
app.post(
"/user/keyword",
'/user/keyword',
async (req: TypedRequest<keywordIdBody>, res: Response) => {
//get userid from session
const sessionFromDB = await validateSession(
req.session ? req.session : null
);
if (!sessionFromDB) {
return res.status(401).json({ message: "Invalid session provided." });
return res.status(401).json({ message: 'Invalid session provided.' });
}
const userID = sessionFromDB.userId;

Expand All @@ -1306,7 +1317,7 @@ app.post(
});

if (!keywordExists) {
return res.status(404).json({ message: "Invalid keyword." });
return res.status(404).json({ message: 'Invalid keyword.' });
}

//Connect keyword and user
Expand Down Expand Up @@ -1336,19 +1347,20 @@ app.post(
},
});

return res.status(200).json({ message: "ok" });
});
return res.status(200).json({ message: 'ok' });
}
);

// disassociates a user with a keyword
app.delete(
"/user/keyword",
'/user/keyword',
async (req: TypedRequest<keywordIdBody>, res: Response) => {
//get userid from session
const sessionFromDB = await validateSession(
req.session ? req.session : null
);
if (!sessionFromDB) {
return res.status(401).json({ message: "Invalid session provided." });
return res.status(401).json({ message: 'Invalid session provided.' });
}
const userID = sessionFromDB.userId;

Expand All @@ -1363,7 +1375,7 @@ app.delete(
});

if (!societyId) {
return res.status(400).json({ message: "Invalid keyword." });
return res.status(400).json({ message: 'Invalid keyword.' });
}

//Disconnect keyword and user
Expand Down Expand Up @@ -1393,8 +1405,9 @@ app.delete(
},
});

return res.status(200).json({ message: "ok" });
});
return res.status(200).json({ message: 'ok' });
}
);

app.get('/hello', () => {
console.log('Hello World!');
Expand Down
Loading

0 comments on commit f3578b4

Please sign in to comment.