1- import { Application , Router } from 'https://deno.land/x/oak/mod.ts'
1+ import { Application , Router , helpers , RouterContext , RouteParams } from 'https://deno.land/x/oak/mod.ts'
22
33const env = Deno . env . toObject ( )
44const HOST = env . HOST || '0.0.0.0'
@@ -26,9 +26,10 @@ let books: Array<IBook> = [{
2626
2727const searchBookById = ( id : string ) : ( IBook | undefined ) => books . filter ( book => book . id === id ) [ 0 ]
2828
29- const getBook = ( { params, response } : { params : { id : string } ; response : any } ) => {
30- console . log ( params )
31- const book : IBook | undefined = searchBookById ( params . id )
29+ const getBook = ( ctx : RouterContext < any > ) => {
30+ const { response } : { response : any } = ctx ;
31+ const query = helpers . getQuery ( ctx ) ;
32+ const book : IBook | undefined = searchBookById ( query . id )
3233 if ( book ) {
3334 response . status = 200
3435 response . body = book
@@ -38,10 +39,34 @@ const getBook = ({ params, response }: { params: { id: string }; response: any }
3839 }
3940}
4041
42+ const postBook = async ( ctx : RouterContext < RouteParams > ) => {
43+ const { request, response } = ctx ;
44+ if ( request . hasBody ) {
45+ const result : any = await request . body ( {
46+ contentTypes : {
47+ text : [ "application/javascript" ] ,
48+ } ,
49+ } ) ;
50+ const body : any = JSON . parse ( result . value )
51+ const book : IBook | undefined = searchBookById ( body . id )
52+ console . log ( body )
53+ if ( ! book ) {
54+ response . status = 200
55+ response . body = body
56+ } else {
57+ response . status = 422
58+ response . body = { message : `Book already exists.` }
59+ }
60+ } else {
61+ response . status = 422
62+ response . body = { message : `Can't parse body.` }
63+ }
64+ }
65+
4166const router = new Router ( )
42- router . get ( '/books/:id' , getBook )
67+ router . get ( '/books' , getBook )
68+ . post ( '/books' , postBook )
4369// .get('/books', getBooks)
44- // .post('/books', addBook)
4570// .put('/books/:id', updateBook)
4671// .delete('/books/:id', deleteBook)
4772
0 commit comments