Making REST API Call with KOA

Highlighted
New Member
3 0 0

Hey,

 

I am building a custom application. Originally I built this with express but I have to change this to KOA.

 

With express, I was able to set up, fetch and post to my store. However, now that I have to move to Koa I am unable to figure out how to make the routing work correctly. I've looked around for information on using REST APIs with Shopify and the only information I was able to find is about webhooks, which didn't shed much light on my issue.

 

Here is the code that I am working with to try and get this to work, currently it returns a 404 (The router isn't initialising maybe?)

 

require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');
const request = require('request-promise');

dotenv.config();

const Router = require('koa-router');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY, HOST } = process.env;

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  server.use(session({ secure: true, sameSite: 'none' }, server));
  server.keys = [SHOPIFY_API_SECRET_KEY];

  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET_KEY,
      scopes: ['read_products, write_content'],
      afterAuth(ctx) {
        const { shop, accessToken } = ctx.session;

        ctx.redirect('../../../Step1');
      },
    }),
  );

  router.use('/getBlogs', (ctx, next) => {
    const shopRequestUrl = `https://${ctx.shop}/admin/api/2020-01/blogs.json`;
    const shopRequestHeaders = {
      'X-Shopify-Access-Token': ctx.accessToken,
    };
  
    request.get({
      url: shopRequestUrl,
      headers: shopRequestHeaders
    }).then((shopResponse) => {
        res.status(200).end(shopResponse);
    })
    .catch((error) => {
        res.status(error.statusCode).send(error.error.error_description);
    });
  })

  server.use(router.routes());
  server.use(router.allowedMethods());
  server.use(verifyRequest());
  server.use(async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
    return
  });

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

 

0 Likes
Highlighted
New Member
3 0 0

Figured this out. This can be closed.

0 Likes