【问题标题】:How to pass ctx / context into KOA middleware that is imported (createShopifyAuth)?如何将 ctx / context 传递到导入的 KOA 中间件(createShopifyAuth)?
【发布时间】:2021-01-24 00:58:09
【问题描述】:

我希望将请求上下文传递到由 require (https://github.com/Shopify/koa-shopify-auth) 生成的 KOA 中间件。我设置了一些 API 密钥,我需要从以前的中间件传递给它,但是当我到达 createShopifyAuth 时无法访问它们。

我尝试过传入全局 server.context,但它似乎不是从以前的中间件设置的。

server.use(async (ctx, next) => {
    await shopifyKeys;
    if (url.parse(ctx.originalUrl, true).query.shop) {
      const shops = url.parse(ctx.originalUrl, true).query.shop;
      server.context.keys = [shopifyKeys[shops].key, shopifyKeys[shops].secret];
      console.log(server.context.keys);
    }
    return next();
  });

server.use(
  createShopifyAuth({
    apiKey: server.context.keys[0],
    secret: server.context.keys[1],
    scopes: [
      'read_products',
      'read_checkouts',
      'read_orders',
      'write_orders',
    ],
    async afterAuth(ctx) {
      const { shop, accessToken } = ctx.session;
      ctx.cookies.set('shopOrigin', shop, {
        httpOnly: false,
        secure: true,
        sameSite: 'none',
      });
      const registration = await registerWebhook({
        address: `${HOST}/webhooks/orders/paid`,
        topic: 'ORDERS_PAID',
        accessToken,
        shop,
        apiVersion: ApiVersion.July20,
      });

      if (registration.success) {
        console.log('Successfully registered webhook!');
      } else {
        console.log(
          'Failed to register webhook',
          registration.result.data.webhookSubscriptionCreate.userErrors,
        );
      }
      ctx.redirect('/');
    },
  }),
); 

任何有关如何将上下文获取到第二个 server.use 的帮助将不胜感激。

【问题讨论】:

    标签: shopify next.js koa shopify-app


    【解决方案1】:

    据说我是 KOA 的新手,但我设法做到这一点的唯一方法是通过 cookie 传递数据,单独。这是一个例子:

      server.use(
        createShopifyAuth({
          apiKey: SHOPIFY_API_KEY,
          secret: SHOPIFY_API_SECRET_KEY,
          scopes: [
            "read_products",
            "write_products",
            "read_script_tags",
            "write_script_tags",
            "read_themes",
            "write_themes",
          ],
          accessMode: "offline",
    
          afterAuth(ctx) {
            const { shop, accessToken } = ctx.session;
    
            ctx.cookies.set("shopOrigin", shop, {
              httpOnly: false,
              secure: true,
              sameSite: "none",
            });
    
            ctx.cookies.set("accessToken", accessToken, {
              httpOnly: false,
              secure: true,
              sameSite: "none",
            });
    
            ctx.redirect("/");
          },
        }),
      );
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多