documentation icon indicating copy to clipboard operation
documentation copied to clipboard

[Request]: Use arrow functions at controller implementation examples instead normal javascript functions

Open lgemc opened this issue 3 years ago • 0 comments

Summary

Problem

Implementing backend based in doc controllers implementation examples can be confusing in some escenarios where context state is needed.

Where it can occurs When normal functions are used at controllers, some part of ctx object remains hidden to function.

Example (assuming an authorized request):

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

module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) =>  ({
  // Method 1: Creating an entirely custom action
  async exampleAction(ctx) {
    try {
      strapi.log.info(ctx.state.user); // will end in failure because state is undefined
    } catch (err) {
      ctx.body = err;
    }
  }, 
  ...

In contrast, at this example, context is fully available

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

module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) =>  ({
// Method 1: Creating an entirely custom action
exampleAction: async (ctx) => {
  try {
    strapi.log.info(ctx.state.user); // here state contains the user object 
  } catch (err) {
    ctx.body = err;
  }
}, 
...

Why is it needed?

Readers implementing backend solutions that needs full ctx properties, like ctx.state will be confused when it is undefined where it should not be undefined.

Suggested solution(s)

We can evaluate change the controllers examples implementation to use arrow functions to prevent confusion in our doc readers.

Related issue(s)/PR(s)

No response

lgemc avatar Aug 06 '22 20:08 lgemc