|
/********************************** |
|
* ROUTES |
|
*********************************/ |
|
|
|
app.get('/products', (req, res) => { |
|
let pageAndCount = {page: '1', count: '5'}; |
|
let params = req.url.replace('/products/', '') |
|
params = params.replace('?', '').split('&') |
|
if (params[0] !== '') { |
|
params.forEach(param => { |
|
param = param.split('='); |
|
pageAndCount[param[0]] = param[1]; |
|
}) |
|
} |
|
pageAndCount.count = (Number(pageAndCount.count) > 10 || pageAndCount.count === '')? '10' : pageAndCount.count; |
|
if (isValidParam('products', pageAndCount.page, res)) { |
|
models.getAllProducts(pageAndCount) |
|
.then(result => { |
|
res.status(200).json(result) |
|
}) |
|
.catch(err => { |
|
console.log(new Error(err)) |
|
res.status(500) |
|
}) |
|
} |
|
}) |
|
|
|
|
|
app.get('/products/:product_id', (req, res) => { |
|
let id = req.url.replace('/products/', '') |
|
if (isValidParam('productId', id, res)) { |
|
models.getProductById(id) |
|
.then(result => { |
|
res.status(200).json(result) |
|
}) |
|
.catch(error => { |
|
console.log(new Error(error)) |
|
res.status(500); |
|
}) |
|
} |
|
}) |
|
|
|
|
|
app.get('/products/:product_id/styles', (req, res) => { |
|
let id = req.url.replace('/products/', '').replace('/styles', ''); |
|
if (isValidParam('styles', id, res)) { |
|
models.getProductStyles(id) |
|
.then(results => { |
|
res.status(200).json(results); |
|
}) |
|
.catch(err => { |
|
console.log(new Error(err)) |
|
res.status(500) |
|
}) |
|
} |
|
}) |
|
|
|
|
|
app.get('/products/:product_id/related', (req, res) => { |
|
let id = req.url.replace('/products/', '').replace('/related', ''); |
|
if (isValidParam('related', id, res)) { |
|
models.getRelatedProducts(id) |
|
.then(result => { |
|
res.status(200).json(result); |
|
}) |
|
.catch(err => { |
|
console.log(new Error(err)) |
|
res.sendStatus(500) |
|
}) |
|
} |
|
}) |
Products-API/server.js
Lines 20 to 90 in 0b24ac9
Instead of defining Routes as a section within a file where you're also initializing the server, are there tools that help organize Routes so that our application structure is more modular?