【问题标题】:Strapi v4: How to access context within a serviceStrapi v4:如何访问服务中的上下文
【发布时间】:2022-11-11 06:30:46
【问题描述】:

当我在 Strapi 中创建自定义控制器时,我可以方便地访问 Context 对象,我可以在其中获取当前用户并根据需要使用该用户的数据:

module.exports = createCoreController("api::event.event", ({ strapi }) => ({
  //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.entityService.findMany("api::event.event", {
      filters: {
        user: user.id,
      },
    });

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

    const sanitizedEntity = await sanitize.contentAPI.output(data);

    return { data: sanitizedEntity };
  },
}));

但是,当我通过尝试扩展核心服务来创建自定义服务时,我似乎没有上面的上下文对象:

module.exports = createCoreService("api::event.event", ({ strapi }) => ({
  //https://docs.strapi.io/developer-docs/latest/development/backend-customization/services.html#extending-core-services

  async create(params) {
    console.log("inside event.js - create");
    console.log("params", params);

    console.log("params to save", params);

    // some logic here
    const result = await super.create(params);
    // some more logic

    return result;
  },

  async update(entityId, params) {
    params.data.user = entityId;

    // some logic here
    const result = await super.update(entityId, params);
    // some more logic

    return result;
  },
}));

如果可能的话,我想访问上下文对象,因为我想访问用户信息并获取用户 ID 并将该 ID 添加为该条目的所有者或创建者。

有可能吗?如何做到这一点???

【问题讨论】:

    标签: javascript next.js strapi


    【解决方案1】:

    我也很想知道这一点。你有想过吗?

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2018-02-03
      • 2019-05-19
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2020-04-17
      • 2022-08-04
      • 2019-10-19
      相关资源
      最近更新 更多