backend revamp: pools

This commit is contained in:
Michael Fatemi 2021-04-10 21:43:57 -04:00
parent dd837616af
commit 6b5bc4f405
2 changed files with 58 additions and 60 deletions

View File

@ -4,70 +4,12 @@ import { getGroupByID, getPoolByID, getPoolsWithUser } from '../data';
import { GroupModel, PoolModel } from '../models';
import * as user from './user';
import * as pool from './pool';
export const router = Router();
router.use('/user', user.router);
router.get('/pool', async (req, res) => {
if (typeof req.query.poolID != 'string') {
return;
}
let poolID = req.query.poolID;
let pool = await getPoolByID(poolID);
if (pool) {
res.json({ status: 'success', data: pool });
} else {
res.json({ status: 'error', error: 'not_found' });
}
});
router.post('/pool', (req, res) => {
if (req.session.accountID == null) {
res.status(401);
return res.json({ status: 'error', error: 'need_login' });
}
const userID = req.session.accountID;
const {
capacity,
description,
direction,
end_time,
group_id,
start_time,
title,
type,
} = req.body;
const pool = new PoolModel();
Object.assign(pool, {
author_id: userID,
capacity,
description,
direction,
status: 'pending',
title,
type,
participant_ids: [],
comments: [],
create_time: new Date().toISOString(),
update_time: new Date().toISOString(),
group_id,
});
pool
.save()
.then((pool) => {
res.json({ status: 'success', id: pool._id });
})
.catch((err) => {
console.error('Error when creating a pool:', err);
res.json({ status: 'error' });
});
});
router.use('/pool', pool.router);
router.get('/group', async (req, res) => {
if (typeof req.query.groupID != 'string') {

56
src/api/pool.ts Normal file
View File

@ -0,0 +1,56 @@
import { Router } from 'express';
import { PoolModel } from '../models';
import { ObjectID } from 'mongodb';
import requireApiAuth from '../requireApiAuth';
export const router = Router();
router.get('/:poolID', async (req, res) => {
const pool = await PoolModel.findById(new ObjectID(req.params.poolID)).exec();
if (pool) {
res.json({ status: 'success', data: pool });
} else {
res.json({ status: 'error', error: 'not_found' });
}
});
router.post('/', requireApiAuth, async (req, res) => {
const userID = req.session.accountID;
const {
capacity,
description,
direction,
end_time,
group_id,
start_time,
title,
type,
} = req.body;
const pool = new PoolModel();
Object.assign(pool, {
author_id: userID,
capacity,
description,
direction,
status: 'pending',
title,
type,
participant_ids: [],
comments: [],
create_time: new Date().toISOString(),
update_time: new Date().toISOString(),
group_id,
});
pool
.save()
.then((pool) => {
res.json({ status: 'success', id: pool._id });
})
.catch((err) => {
console.error('Error when creating a pool:', err);
res.json({ status: 'error' });
});
});