-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbook.controller.ts
More file actions
70 lines (55 loc) · 1.58 KB
/
book.controller.ts
File metadata and controls
70 lines (55 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { QueryOrder, wrap } from '@mikro-orm/sqlite';
import Router from 'koa-router';
import { DI } from '../server';
import { z } from 'zod';
const router = new Router();
router.get('/', async ctx => {
ctx.body = await DI.books.findAll({
populate: ['author'],
orderBy: { title: QueryOrder.DESC },
limit: 20,
});
});
router.get('/:id', async ctx => {
try {
const params = z.object({ id: z.coerce.number() }).parse(ctx.params);
const book = await DI.books.findOne(params.id, { populate: ['author'] });
if (!book) {
return ctx.throw(404, { message: 'Book not found' });
}
ctx.body = book;
} catch (e: any) {
console.error(e);
return ctx.throw(400, { message: e.message });
}
});
router.post('/', async ctx => {
const body = (ctx.request as any).body;
if (!body.title || !body.author) {
ctx.throw(400, { message: 'One of `title, author` is missing' });
}
try {
const book = DI.books.create(body);
await DI.em.flush();
ctx.body = book;
} catch (e: any) {
console.error(e);
return ctx.throw(400, { message: e.message });
}
});
router.put('/:id', async ctx => {
try {
const params = z.object({ id: z.coerce.number() }).parse(ctx.params);
const book = await DI.books.findOne(params.id);
if (!book) {
return ctx.throw(404, { message: 'Book not found' });
}
wrap(book).assign((ctx.request as any).body);
await DI.em.flush();
ctx.body = book;
} catch (e: any) {
console.error(e);
return ctx.throw(400, { message: e.message });
}
});
export const BookController = router;