Files
outline/server/routes/api/searches.ts
Apoorv Mishra f4461573de Refactor to accommodate authentication, transaction and pagination states together (#4636)
* fix: refactor to accommodate authentication, transaction and pagination together into ctx.state

* feat: allow passing response type to APIContext
2023-01-04 23:51:44 +05:30

50 lines
1.2 KiB
TypeScript

import Router from "koa-router";
import auth from "@server/middlewares/authentication";
import { SearchQuery } from "@server/models";
import { presentSearchQuery } from "@server/presenters";
import { APIContext } from "@server/types";
import { assertPresent, assertUuid } from "@server/validation";
import pagination from "./middlewares/pagination";
const router = new Router();
router.post("searches.list", auth(), pagination(), async (ctx: APIContext) => {
const { user } = ctx.state.auth;
const searches = await SearchQuery.findAll({
where: {
userId: user.id,
},
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
ctx.body = {
pagination: ctx.state.pagination,
data: searches.map(presentSearchQuery),
};
});
router.post("searches.delete", auth(), async (ctx: APIContext) => {
const { id, query } = ctx.request.body;
assertPresent(id || query, "id or query is required");
if (id) {
assertUuid(id, "id is must be a uuid");
}
const { user } = ctx.state.auth;
await SearchQuery.destroy({
where: {
...(id ? { id } : { query }),
userId: user.id,
},
});
ctx.body = {
success: true,
};
});
export default router;