Ebrahim Heydari
Ebrahim Heydari

Reputation: 13

how to create custom endpoint in strapi v4

I've migrated from strapi v3 to strapi v4 and i wants to create custom endpoint 'events/me' by this code in "src/api/event/controllers" directory:

"use strict";
const { sanitizeEntity } = require("strapi-utils");

module.exports = {
  // Get logged in users
  async me(ctx) {
    const user = ctx.state.user;

    if (!user) {
      return ctx.badRequest(null, [
        { messages: [{ id: "No authorization header was found" }] },
      ]);
    }

    const data = await strapi.services.events.find({ user: user.id });

    if (!data) {
      return ctx.notFound();
    }

    return sanitizeEntity(data, { model: strapi.models.events });
  },
};

but i encountered to this error:

Cannot find module 'strapi-utils'

it seems that "strapi-utils" there isn't in strapi v4.

by addition, there isn't any "cofing/routes.json" file. this has been replaced by "route/event.js" file.

strapi document couldn't help me. Any help would be appreciated

Upvotes: 1

Views: 1700

Answers (1)

Sika
Sika

Reputation: 586

You could import it from @strapi/utils. The sanitize function of Strapi has a bit changed in v4: you have to use the Content API and provide the schema for the sanitized object.

Here you can find an example of use: https://github.com/strapi/strapi/blob/main/packages/plugins/users-permissions/server/controllers/user.js

Upvotes: 1

Related Questions