1
1
import { createServer } from 'http' ;
2
- import { createRouter , Response } from '@whatwg-node/router ' ;
2
+ import { createRouter , Response } from 'fets ' ;
3
3
4
- interface Author {
5
- id : string ;
6
- name : string ;
7
- email : string ;
8
- }
9
-
10
- const authors : Author [ ] = [
4
+ const authors = [
11
5
{
12
6
id : '1' ,
13
7
name : 'John Doe' ,
@@ -21,37 +15,87 @@ const authors: Author[] = [
21
15
] ;
22
16
23
17
async function main ( ) {
24
- const app = createRouter ( ) ;
25
-
26
- app . get (
27
- '/authors' ,
28
- ( ) =>
29
- new Response ( JSON . stringify ( authors ) , {
30
- headers : {
31
- 'Content-Type' : 'application/json' ,
18
+ const app = createRouter ( {
19
+ components : {
20
+ schemas : {
21
+ Author : {
22
+ type : 'object' ,
23
+ properties : {
24
+ id : {
25
+ type : 'string' ,
26
+ } ,
27
+ name : {
28
+ type : 'string' ,
29
+ } ,
30
+ email : {
31
+ type : 'string' ,
32
+ } ,
33
+ } ,
34
+ required : [ 'id' , 'name' , 'email' ] ,
35
+ additionalProperties : false ,
32
36
} ,
33
- } ) ,
34
- ) ;
35
-
36
- app . get ( '/authors/:id' , req => {
37
- const author = authors . find ( author => author . id === req . params . id ) ;
37
+ } ,
38
+ } as const ,
39
+ } )
40
+ . route ( {
41
+ method : 'GET' ,
42
+ path : '/authors' ,
43
+ operationId : 'authors' ,
44
+ description : 'Returns a list of authors' ,
45
+ schemas : {
46
+ responses : {
47
+ 200 : {
48
+ description : 'A list of authors' ,
49
+ type : 'array' ,
50
+ items : {
51
+ $ref : '#/components/schemas/Author' ,
52
+ } ,
53
+ } ,
54
+ } ,
55
+ } as const ,
56
+ handler : ( ) => Response . json ( authors ) ,
57
+ } )
58
+ . route ( {
59
+ method : 'GET' ,
60
+ path : '/authors/:id' ,
61
+ operationId : 'author' ,
62
+ description : 'Returns a single author' ,
63
+ schemas : {
64
+ request : {
65
+ params : {
66
+ type : 'object' ,
67
+ properties : {
68
+ id : {
69
+ type : 'string' ,
70
+ } ,
71
+ } ,
72
+ additionalProperties : false ,
73
+ required : [ 'id' ] ,
74
+ } ,
75
+ } ,
76
+ responses : {
77
+ 200 : {
78
+ description : 'The author' ,
79
+ $ref : '#/components/schemas/Author' ,
80
+ } ,
81
+ } ,
82
+ } as const ,
83
+ handler ( req ) {
84
+ const author = authors . find ( author => author . id === req . params . id ) ;
38
85
39
- if ( ! author ) {
40
- return new Response ( null , {
41
- status : 404 ,
42
- } ) ;
43
- }
86
+ if ( ! author ) {
87
+ return new Response ( null , {
88
+ status : 404 ,
89
+ } ) ;
90
+ }
44
91
45
- return new Response ( JSON . stringify ( author ) , {
46
- headers : {
47
- 'Content-Type' : 'application/json' ,
92
+ return Response . json ( author , { status : 200 } ) ;
48
93
} ,
49
94
} ) ;
50
- } ) ;
51
95
52
96
const server = createServer ( app ) ;
53
97
server . listen ( 4001 , ( ) => {
54
- console . log ( 'Authors service listening on port 4001' ) ;
98
+ console . log ( 'Authors service Swagger UI; http://localhost: 4001/docs ' ) ;
55
99
} ) ;
56
100
}
57
101
0 commit comments