diff --git a/README.md b/README.md index 2d790a7..989e2e5 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ | /users/:id | GET | Return user with the specified id | | /posts | GET | Returns a collection of posts | | /posts/:id | GET | Returns the post with the specified ID | +| /postwithuser/:id | GET | Returns the post with the specified ID and the user data | | /products | GET | Returns a collection of products | | /products/:sku | GET | Returns the products with the specified sku| | /restaurants | GET | Returns a collection of restaurant data | diff --git a/app.js b/app.js index 6343ce4..844fe20 100644 --- a/app.js +++ b/app.js @@ -7,6 +7,7 @@ const cors = require('cors') const indexRouter = require('./routes/index'); const usersRouter = require('./routes/users'); const postsRouter = require('./routes/posts'); +const postWithUserRouter = require('./routes/postwithuser'); const productRouter = require('./routes/products'); const restaurantsRouter = require('./routes/restaurants'); @@ -22,6 +23,7 @@ app.use(cors()) app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/posts', postsRouter); +app.use('/postwithuser', postWithUserRouter); app.use('/products', productRouter) app.use('/restaurants', restaurantsRouter) diff --git a/routes/postwithuser.js b/routes/postwithuser.js new file mode 100644 index 0000000..e91c3a3 --- /dev/null +++ b/routes/postwithuser.js @@ -0,0 +1,38 @@ +const express = require('express'); +const router = express.Router(); +const fs = require('fs') +const posts = JSON.parse(fs.readFileSync('database/posts.json', 'utf-8')) +const users = JSON.parse(fs.readFileSync('database/users.json', 'utf-8')) + +router.get('/', function (req, res, _next) { + res.status(404) + res.json('Add post id to your request - /postwithuser/:id') + return +}); + +/** + * GET post with user data using post_id + */ +router.get('/:post', (req, res, _next) => { + const postId = req.params.post + if (postId == 0 || postId > posts.length) { + res.status(404) + res.json('post Not Found') + return + } + const postWithUserData = posts[postId - 1] + + const userId = posts[postId - 1].user_id + if (userId == 0 || userId > users.length) { + res.status(404) + res.json('User Not Found') + return + } + + postWithUserData.user_data = users[userId - 1] + res.json(postWithUserData) + +}); + + +module.exports = router;