Comments (9)
Assuming you have generated a page
and a book
APIs, it can be done easily by updating few lines on the book api:
- Add
/:id/:resource
route to book.router.js:
router.get('/:id/:resource',
showResource)
- Add a
showResource
method in book.controller.js
export const showResource = ({ params }, res, next) =>
Book.findById(params.id)
.populate(params.resource)
.then(notFound(res))
.then((entity) => book ? book.view()[params.resource] : null)
.then(success(res))
.catch(next)
- Add reference in book.model.js
const bookSchema = new Schema({
pages: [{
type: Schema.ObjectId,
ref: 'Page'
}]
}, {
timestamps: true
})
bookSchema.methods = {
view () {
const view = {
// simple view
id: this.id,
pages: this.pages ? this.pages.view() : undefined,
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
return view
}
}
I didn't test this code, but it should work. It can be optimized though.
Also, It would be nice if we could do this with the generator. I just need more use cases. I would be grateful if you share your code (or a snippet) when you finish. :)
from rest.
Okay thanks... I will when I do.
But that will work just for embedding a page in a book response, it won't create extra routes, for instance creating a new page on a related book, POST /books/{bookId}/pages
?
from rest.
In an easy way, you can reimplement the logic from POST /pages
to the books API.
In the example I posted, you can GET /books/:id/pages
. I've updated the answer.
from rest.
Okay, I will try that. Thanks for the prompt response.
from rest.
can you provide an example of what the Page Schema looks like to complete the example?
from rest.
@aaronksaunders It should work with a simple one generated with yo rest:api
from rest.
i guess i am confused with how the relationship is saved since there is not an example of POST for the
In an easy way, you can reimplement the logic from POST /pages to the books API.
not sure what exactly this means?
from rest.
Hi, @aaronksaunders
If you generate an API with yo rest:api
it will create something like:
page.router.js
// grabs schema fields from the model
const { title, content } = schema.tree
// enables the route POST /pages
router.post('/',
body({ title, content }),
create)
page.controller.js
export const create = ({ bodymen: { body } }, res, next) =>
Page.create(body)
.then((page) => page.view(true))
.then(success(res, 201))
.catch(next)
And this is the logic behind POST /pages
.
To implement this on POST /books/:id/pages
, you need to make something like:
book.router.js
import { schema as pageSchema } from '../page'
// grabs schema fields from the page model
const { title, content } = pageSchema.tree
// enables the route POST /books/:id/pages
router.post('/:id/pages',
body({ title, content }),
createPage)
book.controller.js
import { Page } from '../page'
export const createPage = ({ params, bodymen: { body } }, res, next) =>
Book.findById(params.id)
.then(notFound(res))
.then((book) => {
if (!book) return null // book wasn't found
// create page from request body
return Page.create(body).then((page) => {
// add page to book.pages
book.pages.addToSet(page)
return book.save()
})
})
.then((book) => book ? book.view(true).pages : null)
.then(success(res, 201))
.catch(next)
It should be enough. I wrote this directly on GitHub, then it may contain some errors.
We can improve this code and add this to the generator, but I want to see how the people use this, because I usually don't make requests this way (I would first create the page POST /pages
and then update the book PUT /books
).
If you want to learn more about the code, please refer to this repo: https://github.com/diegohaz/generator-rest-example
It has the generated code with some comments.
from rest.
Hi, I'm trying a similar action like add a comment to post where I´ve comments:[] .
POST /posts/:id/comment this endpoint will push the comment reference to the post but I can't make it works.
thanks !
from rest.
Related Issues (20)
- Error Handling
- Can querymen automatically handle lowercase vs uppercase searches HOT 4
- use jsdoc with openapi/swagger for documentation (feature) HOT 2
- Change login request from POST to GET HOT 4
- test KO just after creation
- test KO after creating the API HOT 4
- MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms HOT 5
- Heroku no MongoLab addon HOT 2
- No return through with GET request HOT 1
- Debugging with vscode | es6 imported variables not visible by the debugger HOT 1
- same issue HOT 2
- Patch methode -> change one field
- How to GET random user
- nodemailer email integration
- How to add reference model HOT 1
- Annotations don't contain dataType in case fo yo rest:api HOT 1
- ImportError : Couldn't import Django
- No default language could be detected for this app
- [ts] Declaration or statement expected. [1128]
- I had a problem in vs HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from rest.