orangecat
orangecat

Reputation: 1

Strapi POST relations

I have a problem with posting relations in Strapi.

I have a todo and a person, person has many todos.

When i try to post new todo in Postman, i get this response:

{
    "data": null,
    "error": {
        "status": 400,
        "name": "ValidationError",
        "message": "1 relation(s) of type api::person.person associated with this entity do not exist",
        "details": {
            "errors": [
                {
                    "path": [],
                    "message": "1 relation(s) of type api::person.person associated with this entity do not exist",
                    "name": "ValidationError"
                }
            ]
        }
    }
}

I can post with id of existing person, but cannot if i want to post new person and a new todo.

Upvotes: 0

Views: 1593

Answers (1)

antokhio
antokhio

Reputation: 2004

This seems by design, however haven’t been able to find out if that should work, you can check my issue. I suspect this was not implemented yet. So you have two options here:

  1. Handle in frontend (e.g. first post person, then post task, with entity id)
  2. Handle in backend via custom controller:

/src/api/todo/controllers/todo.js

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::todo.todo', ({ strapi }) => ({
  async create(ctx) {
    const { data } = ctx.request.body;
    let { person, ...todo } = data;
    
    if (person) // if there is person
      if (typeof person === 'object') // if person is object create person otherwise have it as id
        person = await strapi.entityService.create('api::person.person', { data: person });
    // create todo and add person as id or as newly created object
    todo = await strapi.entityService.create('api::todo.todo', { data: { ...todo, person }, populate: ['person']);
    
    // optional: remove sensitive data 
    // todo = await this.sanitizeOutput(todo, ctx);
    // optional: convert response to data / attributes structure
    // todo = this.transformResponse(todo);

    return todo;
  },

Usage should be straightforward: /api/todos POST body: { data: { …todoData, person: {…personData }}}

Upvotes: 0

Related Questions