1
+ const express = require ( 'express' )
2
+ const app = express ( )
3
+ const port = process . env . port || 3002
4
+
5
+ let products = [
6
+ { name : 'Television' , brand : "LG" }
7
+ , { name : 'Washing Machine' , brand : "Samsung" }
8
+ , { name : 'Laptop' , brand : "Apple" }
9
+ ] ;
10
+
11
+ app . use ( express . json ( ) )
12
+
13
+ app . get ( '/products' , ( req , res ) => {
14
+ res . json ( products )
15
+ } )
16
+
17
+ app . get ( '/products/deals' , ( req , res ) => {
18
+ res . json ( products )
19
+ } )
20
+
21
+ app . get ( '/products/:name' , ( req , res ) => {
22
+ const name = req . params . name
23
+ let matchedProduct = products . find ( prod => prod . name == name )
24
+ matchedProduct . price = ( Math . random ( ) * 1000 ) . toFixed ( 2 )
25
+ res . json ( matchedProduct )
26
+ } )
27
+
28
+ app . post ( '/products' , ( req , res ) => {
29
+
30
+ console . log ( req . headers )
31
+
32
+ const name = req . body . name
33
+ const brand = req . body . brand
34
+
35
+ const product = { name : name , brand :brand }
36
+ products . push ( product )
37
+ res . send ( { result :"OK" } )
38
+ } )
39
+
40
+ app . get ( '/products/:name/itemsInStock' , ( req , res ) => {
41
+ const name = req . params . name
42
+ let matchedProduct = products . find ( prod => prod . name == name )
43
+ matchedProduct . unitsInStock = ( Math . random ( ) * 1000 ) . toFixed ( 0 )
44
+ res . json ( matchedProduct )
45
+ } )
46
+
47
+
48
+ app . listen ( port , ( ) => {
49
+ console . log ( `API server listening on port ${ port } ` )
50
+ } )
0 commit comments