GithubHelp home page GithubHelp logo

Support for model relations about rest HOT 9 CLOSED

diegohaz avatar diegohaz commented on May 13, 2024
Support for model relations

from rest.

Comments (9)

diegohaz avatar diegohaz commented on May 13, 2024

Assuming you have generated a page and a book APIs, it can be done easily by updating few lines on the book api:

  1. Add /:id/:resource route to book.router.js:
router.get('/:id/:resource',
  showResource)
  1. 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)
  1. 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.

habbes avatar habbes commented on May 13, 2024

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.

diegohaz avatar diegohaz commented on May 13, 2024

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.

habbes avatar habbes commented on May 13, 2024

Okay, I will try that. Thanks for the prompt response.

from rest.

aaronksaunders avatar aaronksaunders commented on May 13, 2024

can you provide an example of what the Page Schema looks like to complete the example?

from rest.

diegohaz avatar diegohaz commented on May 13, 2024

@aaronksaunders It should work with a simple one generated with yo rest:api

from rest.

aaronksaunders avatar aaronksaunders commented on May 13, 2024

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.

diegohaz avatar diegohaz commented on May 13, 2024

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.

eliascalabrese avatar eliascalabrese commented on May 13, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.