Skip to content

Commit

Permalink
✨ Add new route /data/sync that combines getting and posting entries
Browse files Browse the repository at this point in the history
  • Loading branch information
Importantus committed Sep 23, 2024
1 parent 3fb6448 commit 56cfefb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/routes/v1/data.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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;
6 changes: 6 additions & 0 deletions src/validators/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof getDataQuery>;
export type syncDataQueryType = s.Infer<typeof syncDataQuery>;

0 comments on commit 56cfefb

Please sign in to comment.