diff --git a/server/api/points/index.ts b/server/api/points/index.ts index 2b51165..35c690a 100644 --- a/server/api/points/index.ts +++ b/server/api/points/index.ts @@ -2,7 +2,7 @@ import { Middleware } from 'koa' import Router from 'koa-router' import PointModel, { - PointDocument, + PointDocument, // PointType, } from '../../models/points' @@ -10,16 +10,21 @@ import { Props, } from '@types' + +import { validTopDays, validUserDays, validGetUser } from '../../utils/points/validators' + export default (props: Props): Middleware => { const router = new Router() const { - + } = props - + // TODO: validate input router.get('/:id', async ctx => { + if (!validGetUser(ctx.params)) return ctx.throw(400) + const points: PointDocument[] | null = await PointModel.find({ userID: ctx.params.id }) if (points?.length > 0) ctx.body = points @@ -27,8 +32,11 @@ export default (props: Props): Middleware => { }) router.get('/user/:id/:days', async ctx => { + if (!validUserDays(ctx.params)) return ctx.throw(400) + + const date = new Date(Date.now() - Number(ctx.params.days) * 24 * 60 * 60 * 1000) - + const points: PointDocument[] | null = await PointModel.find({ userID: ctx.params.id, createdAt: { $gte: date.toISOString() }, @@ -39,16 +47,16 @@ export default (props: Props): Middleware => { }) router.get('/top/:days', async ctx => { - const date = new Date(Date.now() - Number(ctx.params.days) * 24 * 60 * 60 * 1000) + if (!validTopDays(ctx.params)) return ctx.throw(400) - /* TODO: Type all of this */ + const date = new Date(Date.now() - Number(ctx.params.days) * 24 * 60 * 60 * 1000) const { results } = await PointModel.mapReduce({ map: "function () { emit(this.userID, this.amount) }", reduce: "function (_, values) { return Array.sum(values) }", query: { - createdAt: { + createdAt: { $gte: date.toISOString(), }, }, diff --git a/server/utils/points/validators.ts b/server/utils/points/validators.ts new file mode 100644 index 0000000..fbcfb35 --- /dev/null +++ b/server/utils/points/validators.ts @@ -0,0 +1,22 @@ +const validGetUser = (params): boolean => { + if (!Object.keys(params).includes('id')) return false + + return true +} + +const validUserDays = (params): boolean => { + if (!Object.keys(params).includes('days')) return false + if (typeof params.days !== 'string') return false + + return true +} + +const validTopDays = (params): boolean => { + if (!Object.keys(params).includes('days')) return false + if (typeof params.days !== 'string') return false + + return true +} + + +export { validGetUser, validUserDays, validTopDays }