1+ const express = require ( 'express' ) ;
2+ const { uuid, isUuid } = require ( 'uuidv4' ) ;
3+
4+ const app = express ( ) ;
5+
6+ app . use ( express . json ( ) ) ;
7+
8+ const projects = [ ] ;
9+
10+ function logRequests ( request , response , next ) {
11+ const { method, url } = request ;
12+
13+ const logLabel = `[${ method . toUpperCase ( ) } ] ${ url } ` ;
14+
15+ console . time ( logLabel ) ;
16+
17+ next ( ) ;
18+
19+ console . timeEnd ( logLabel )
20+ }
21+
22+ function validateProjectId ( request , response , next ) {
23+ const { id } = request . params ;
24+
25+ if ( ! isUuid ( id ) ) {
26+ return response . status ( 400 ) . json ( { error :'Invalid project ID' } )
27+ }
28+ }
29+
30+ app . use ( logRequests )
31+ app . use ( '/projects/:id' , validateProjectId ) ;
32+
33+ app . get ( '/projects' , ( request , response ) => {
34+
35+ const { title } = request . query ;
36+
37+ const results = title
38+
39+ ? projects . filter ( project => project . title . includes ( title ) )
40+ : projects ;
41+
42+
43+ return response . json ( results ) ;
44+ } ) ;
45+
46+ app . post ( '/projects' , ( request , response ) => {
47+
48+ const { title, owner } = request . body ;
49+
50+ const project = { id : uuid ( ) , title, owner }
51+
52+ projects . push ( project ) ;
53+
54+
55+ return response . json ( project )
56+ } )
57+
58+ app . put ( '/projects/:id' , ( request , response ) => {
59+
60+ const { id } = request . params ;
61+ const { title, owner } = request . body ;
62+
63+ const projectIndex = projects . findIndex ( project => project . id === id ) ;
64+
65+ if ( projectIndex < 0 ) {
66+ return response . status ( 400 ) . json ( { error : 'Project not found' } )
67+ }
68+
69+ const project = {
70+ id,
71+ title,
72+ owner,
73+ }
74+
75+ projects [ projectIndex ] = project
76+
77+ return response . json ( project )
78+ } )
79+
80+ app . delete ( '/projects/:id' , ( request , response ) => {
81+
82+ const { id } = request . params ;
83+
84+ const projectIndex = projects . findIndex ( project => project . id === id ) ;
85+
86+ if ( projectIndex < 0 ) {
87+ return response . status ( 400 ) . json ( { error : 'Project not found' } )
88+ }
89+
90+ projects . splice ( projectIndex , 1 ) ;
91+
92+ return response . status ( 200 ) . send ( ) ;
93+ } )
94+
95+
96+ app . listen ( 3333 , ( ) => {
97+ console . log ( '🚀 back-end started!' )
98+ } ) ;
0 commit comments