-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcreatePosting.tsx
More file actions
60 lines (52 loc) · 1.64 KB
/
createPosting.tsx
File metadata and controls
60 lines (52 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { firestore, auth } from 'firebase-admin';
import { NextApiRequest, NextApiResponse } from 'next';
import initializeApi from '../../../lib/admin/init';
import { userIsAuthorized } from '../../../lib/authorization/check-authorization';
initializeApi();
const db = firestore();
const POSTINGS_COLLECTION = '/postings';
interface PostingData {
authorId: string;
postingId: string;
numberOfPeopleWanted: number;
skillSet: string;
}
async function createPosting(req: NextApiRequest, res: NextApiResponse, authorId: string) {
try {
const postingData: PostingData = JSON.parse(req.body);
postingData.authorId = authorId;
await db.collection(POSTINGS_COLLECTION).add(postingData);
return res.status(201).json({
msg: 'Posting created',
});
} catch (error) {
return res.status(500).json({
msg: 'Unexpected error. Please try again later',
});
}
}
async function handlePostRequest(req: NextApiRequest, res: NextApiResponse) {
const userToken = req.headers['authorization'] as string;
const isAuthorized = await userIsAuthorized(userToken, ['hacker']);
const authorId = await auth().verifyIdToken(userToken);
if (!isAuthorized) {
return res.status(403).json({
statusCode: 403,
msg: 'Request is not authorized to perform admin functionality',
});
}
return createPosting(req, res, authorId.uid);
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req;
switch (method) {
case 'POST': {
return handlePostRequest(req, res);
}
default: {
return res.status(404).json({
msg: 'Route not found',
});
}
}
}