diff --git a/src/api/index.ts b/src/api/index.ts index 7b0bad1..0172191 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -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') { diff --git a/src/api/pool.ts b/src/api/pool.ts new file mode 100644 index 0000000..893bb4f --- /dev/null +++ b/src/api/pool.ts @@ -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' }); + }); +});