-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathauthor.controller.ts
More file actions
71 lines (56 loc) · 1.65 KB
/
author.controller.ts
File metadata and controls
71 lines (56 loc) · 1.65 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
71
import { QueryOrder } from '@mikro-orm/sqlite';
import Router from 'koa-router';
import { DI } from '../server';
import { Author } from '../entities';
import { z } from 'zod';
const router = new Router();
router.get('/', async ctx => {
ctx.body = await DI.authors.findAll({
populate: ['books'],
orderBy: { name: QueryOrder.DESC },
limit: 20,
});
});
router.get('/:id', async ctx => {
try {
const params = z.object({ id: z.coerce.number() }).parse(ctx.params);
const author = await DI.authors.findOne(params.id, { populate: ['books'] });
if (!author) {
return ctx.throw(404, { message: 'Author not found' });
}
ctx.body = author;
} 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.name || !body.email) {
return ctx.throw(400, { message: 'One of `name, email` is missing' });
}
try {
const author = DI.em.create(Author, body);
await DI.em.flush();
ctx.body = author;
} 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 author = await DI.authors.findOne(params.id);
if (!author) {
return ctx.throw(404, { message: 'Author not found' });
}
DI.em.assign(author, (ctx.request as any).body);
await DI.em.flush();
ctx.body = author;
} catch (e: any) {
console.error(e);
return ctx.throw(400, { message: e.message });
}
});
export const AuthorController = router;