0

I am creating a node API connecting to a mySql db using Sequelize. I want users of the API to be able to specify which models to include in the results of a query. For example I have a model like this:

Student.init({
    userID: DataTypes.INTEGER,
    name: DataTypes.STRING,
    gradeID: DataTypes.INTEGER
}

I want the user to be able to specify if they want to include the full User and/or Grade objects when querying Students like this:

http://localhost/api/students?include=Grade,User

How would I go about doing this within the controller using Sequelize?

1 Answer 1

0

I'd start with something like this:

  1. Define all needed associations with explicit aliases

  2. Make a dictionary of model descriptions with: resource name (from url) as a key, and a model reference and and a dictionary as values with query param name as a key and an object as a value with an association alias and its model reference

  3. On a request extract a resource name and `include` query param values and use both of them to get a model reference and all included models with their respective aliases.

Something like:


const modelDescriptions = {
  "students": {
    "model": Student,
    "Grade": {
       "model": Grade,
       "alias": "Grade"
    },
    "User": {
       "model": User,
       "alias": "User"
    },
  }
}

const modelDesc = modelDescriptions[resourceName]
const model = modelDesc.model
const includeOptions = includeQueryParamValues.map(x => ({
  model: modelDesc[x].model,
  as: modelDesc[x].alias
}))
const items = await model.findAll({
  include: includeOptions
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.