1
- import { QueryOrder } from '@mikro-orm/core ' ;
1
+ import { QueryOrder } from '@mikro-orm/better-sqlite ' ;
2
2
import { Context } from 'koa' ;
3
3
import Router from 'koa-router' ;
4
4
5
5
import { DI } from '../server' ;
6
6
import { Author } from '../entities' ;
7
+ import { z } from 'zod' ;
7
8
8
9
const router = new Router ( ) ;
9
10
10
11
router . get ( '/' , async ( ctx : Context ) => {
11
- ctx . body = await DI . authorRepository . findAll ( [ 'books' ] , { name : QueryOrder . DESC } , 20 ) ;
12
+ ctx . body = await DI . authors . findAll ( {
13
+ populate : [ 'books' ] ,
14
+ orderBy : { name : QueryOrder . DESC } ,
15
+ limit : 20 ,
16
+ } ) ;
12
17
} ) ;
13
18
14
19
router . get ( '/:id' , async ( ctx : Context ) => {
15
20
try {
16
- const author = await DI . authorRepository . findOne ( ctx . query . id , [ 'books' ] ) ;
21
+ const query = z . object ( { id : z . number ( ) } ) . parse ( ctx . query ) ;
22
+ const author = await DI . authors . findOne ( query . id , { populate : [ 'books' ] } ) ;
17
23
18
24
if ( ! author ) {
19
25
return ctx . throw ( 404 , { message : 'Author not found' } ) ;
20
26
}
21
27
22
28
ctx . body = author ;
23
- } catch ( e ) {
29
+ } catch ( e : any ) {
24
30
console . error ( e ) ;
25
31
return ctx . throw ( 400 , { message : e . message } ) ;
26
32
}
@@ -33,28 +39,29 @@ router.post('/', async (ctx: Context) => {
33
39
34
40
try {
35
41
const author = DI . em . create ( Author , ctx . request . body ) ;
36
- await DI . authorRepository . persist ( author ) . flush ( ) ;
42
+ await DI . em . flush ( ) ;
37
43
38
44
ctx . body = author ;
39
- } catch ( e ) {
45
+ } catch ( e : any ) {
40
46
console . error ( e ) ;
41
47
return ctx . throw ( 400 , { message : e . message } ) ;
42
48
}
43
49
} ) ;
44
50
45
51
router . put ( '/:id' , async ( ctx : Context ) => {
46
52
try {
47
- const author = await DI . authorRepository . findOne ( ctx . params . id ) ;
53
+ const query = z . object ( { id : z . number ( ) } ) . parse ( ctx . query ) ;
54
+ const author = await DI . authors . findOne ( query . id ) ;
48
55
49
56
if ( ! author ) {
50
57
return ctx . throw ( 404 , { message : 'Author not found' } ) ;
51
58
}
52
59
53
60
DI . em . assign ( author , ctx . request . body ) ;
54
- await DI . authorRepository . persist ( author ) . flush ( ) ;
61
+ await DI . em . flush ( ) ;
55
62
56
63
ctx . body = author ;
57
- } catch ( e ) {
64
+ } catch ( e : any ) {
58
65
console . error ( e ) ;
59
66
return ctx . throw ( 400 , { message : e . message } ) ;
60
67
}
0 commit comments