diff --git a/src/routes/v1/data.ts b/src/routes/v1/data.ts index 7882e41..27d5ece 100644 --- a/src/routes/v1/data.ts +++ b/src/routes/v1/data.ts @@ -1,7 +1,7 @@ import * as express from 'express' import h from '../../utils/errorHelper' import { assert } from 'superstruct'; -import { getDataQuery } from '../../validators/data'; +import { getDataQuery, syncDataQuery } from '../../validators/data'; import APIError from '../../utils/apiError'; import { createData, getDataFromGroup } from '../../models/data'; @@ -27,4 +27,26 @@ router.post("/", h(async (req, res) => { res.status(201).json(); })); +router.post("/sync", h(async (req, res) => { + const request = req.body; + + try { + assert(request, syncDataQuery); + } catch (error) { + throw APIError.badRequest(error); + } + + const createdEntries = await createData(res.locals.groupId, request.data); + const data = await getDataFromGroup(res.locals.groupId, { from: request.lastSync, to: "" }); + + // Filter out all doublicates between createdEntries and data + const filteredData = data.filter((entry) => { + return !createdEntries.some((createdEntry) => { + return createdEntry === entry.id; + }); + }); + + res.status(createdEntries.length > 0 ? 201 : 200).json(filteredData); +})); + export default router; \ No newline at end of file diff --git a/src/validators/data.ts b/src/validators/data.ts index 21c77c7..28cde67 100644 --- a/src/validators/data.ts +++ b/src/validators/data.ts @@ -13,5 +13,11 @@ export const getDataQuery = s.object({ to: s.optional(timestamp), }); +export const syncDataQuery = s.object({ + lastSync: timestamp, + data: s.array(s.any()) +}) + export type getDataQueryType = s.Infer; +export type syncDataQueryType = s.Infer;