Every back-end service in existence has some form of system in place that enables them to receive requests and act on them appropriately (providing some response). Services, routes, and controllers are all represented in such servers. Strapi also has this system in place and offers ways for you to customize them to your preferences, such as adding capabilities or developing new ones.
Iām wondering - when I create a custom controller and use the entity service - the return format is not the same as when you use Strapiās default controllers. You know, by default you get your return object wrapped in data- and attributes-fields. When using entity service, you get a more āflatā return object.
Do you know if thereās a way to convert this flatter object to a format like { data: { attributes: ā¦ }, meta: } (like the default controllers)?
async find(ctx) {
// validateQuery throws an error if any of the query params used are inaccessible to ctx.user
// That is, trying to access private fields, fields they don't have permission for, wrong data type, etc
await this.validateQuery(ctx);
// sanitizeQuery silently removes any query params that are invalid or the user does not have access to
// It is recommended to use sanitizeQuery even if validateQuery is used, as validateQuery allows
// a number of non-security-related cases such as empty objects in string fields to pass, while sanitizeQuery
// will remove them completely
const sanitizedQueryParams = await this.sanitizeQuery(ctx);
// Perform whatever custom actions are needed
const { results, pagination } = await strapi
.service("api::restaurant.restaurant")
.find(sanitizedQueryParams);
// sanitizeOutput removes any data that was returned by our query that the ctx.user should not have access to
const sanitizedResults = await this.sanitizeOutput(results, ctx);
// transformResponse correctly formats the data and meta fields of your results to return to the API
return this.transformResponse(sanitizedResults, { pagination });
},
You can also use super when updating a controller based an existing controller to extend it.
async find(ctx) {
// your custom logic for modifying the input
ctx.query = { ...ctx.query, locale: "en" }; // force ctx.query.locale to 'en' regardless of what was requested
// Call the default parent controller action
const result = await super.find(ctx);
// your custom logic for modifying the output
result.meta.date = Date.now(); // change the date that is returned
return result;
},