1+ import { router } from '@stackpress/ingest/fetch' ;
2+
3+ const route = router ( ) ;
4+
5+ let id = 0 ;
6+
7+ /**
8+ * Example user API search
9+ */
10+ route . get ( '/user' , function UserSearch ( req , res ) {
11+ //get filters
12+ //const filters = req.query.get<Record<string, unknown>>('filter');
13+ //maybe get from database?
14+ const results = [
15+ {
16+ id : 1 ,
17+ name : 'John Doe' ,
18+ age : 21 ,
19+ created : new Date ( ) . toISOString ( )
20+ } ,
21+ {
22+ id : 2 ,
23+ name : 'Jane Doe' ,
24+ age : 30 ,
25+ created : new Date ( ) . toISOString ( )
26+ }
27+ ] ;
28+ //send the response
29+ res . setRows ( results , 100 ) ;
30+ } ) ;
31+
32+ /**
33+ * Example user API create (POST)
34+ * Need to use Postman to see this...
35+ */
36+ route . post ( '/user' , function UserCreate ( req , res ) {
37+ //get form body
38+ const form = req . data ( ) ;
39+ //maybe insert into database?
40+ const results = { ...form , id : ++ id , created : new Date ( ) . toISOString ( ) } ;
41+ //send the response
42+ res . setResults ( results ) ;
43+ } ) ;
44+
45+ /**
46+ * Example user API detail
47+ */
48+ route . get ( '/user/:id' , function UserDetail ( req , res ) {
49+ //get params
50+ const id = parseInt ( req . data ( 'id' ) || '' ) ;
51+ if ( ! id ) {
52+ res . setError ( 'ID is required' ) ;
53+ return ;
54+ }
55+ //maybe get from database?
56+ const results = {
57+ id : id ,
58+ name : 'John Doe' ,
59+ age : 21 ,
60+ created : new Date ( ) . toISOString ( )
61+ } ;
62+ //send the response
63+ res . setResults ( results ) ;
64+ } ) ;
65+ route . put ( '/user/:id' , function UserUpdate ( req , res ) {
66+ //get params
67+ const id = parseInt ( req . data ( 'id' ) || '' ) ;
68+ if ( ! id ) {
69+ res . setError ( 'ID is required' ) ;
70+ return ;
71+ }
72+ //get form body
73+ const form = req . post ( ) ;
74+ //maybe insert into database?
75+ const results = { ...form , id, created : new Date ( ) . toISOString ( ) } ;
76+ //send the response
77+ res . setResults ( results ) ;
78+ } ) ;
79+
80+ /**
81+ * Example user API delete (DELETE)
82+ * Need to use Postman to see this...
83+ */
84+ route . delete ( '/user/:id' , function UserRemove ( req , res ) {
85+ //get params
86+ const id = parseInt ( req . data ( 'id' ) || '' ) ;
87+ if ( ! id ) {
88+ res . setError ( 'ID is required' ) ;
89+ return ;
90+ }
91+ //maybe get from database?
92+ const results = {
93+ id : 1 ,
94+ name : 'John Doe' ,
95+ age : 21 ,
96+ created : new Date ( ) . toISOString ( )
97+ } ;
98+ //send the response
99+ res . setResults ( results ) ;
100+ } ) ;
101+
102+ export default route ;
0 commit comments