Skip to content

Instantly share code, notes, and snippets.

@tobymarsden
Created May 8, 2020 12:42
Show Gist options
  • Save tobymarsden/165c1fb5003b9b65c94ad400f28d9bec to your computer and use it in GitHub Desktop.
Save tobymarsden/165c1fb5003b9b65c94ad400f28d9bec to your computer and use it in GitHub Desktop.
widgets/routes.js
const router = require('koa-router')();
const knex = require('config/db').knex;
const Widget = require('widgets/model');
const actions = require('actions');
const requireCurrentShop = require('middleware/require-current-shop');
const setupShopifyApi = require('middleware/setup-shopify-api');
const JSONAPISerializer = require('jsonapi-serializer').Serializer;
const serializeErrors = require('actions/errors').serializeErrors;
/**
* Expose the router
*/
module.exports = router;
/**
* Instantiate the serializer which will be passed to the action
*/
const serializer = new JSONAPISerializer('widgets', {
keyForAttribute: 'underscore_case',
attributes: Widget.serializableAttributesAndRelationships(),
shop: { ref: 'id' }
});
/**
* Create
*/
router.post('/widgets\.:ext?', requireCurrentShop, setupShopifyApi, async ctx => {
var widget = await actions.create(Widget, ctx, { shop_id: ctx.state.shop.id });
console.log(widget)
if(widget.get('location') === 'page') { await widget.syncShopifyPage(ctx.state.shopify); }
ctx.state.shop.syncConfigToShopify(ctx.state.shopify);
});
/**
* Update
*/
var updatePath = '/widgets/:id\.:ext?';
var updateAction = async ctx => {
var widget = await Widget.forge({ shop_id: ctx.state.shop.id, id: ctx.params.id }).fetch();
console.log(widget)
await actions.update(Widget, widget, ctx);
console.log(widget)
if(widget.get('location') === 'page') { await widget.syncShopifyPage(ctx.state.shopify); }
ctx.state.shop.syncConfigToShopify();
};
router.put(updatePath, requireCurrentShop, setupShopifyApi, updateAction);
router.patch(updatePath, requireCurrentShop, setupShopifyApi, updateAction);
/**
* Destroy
*/
router.del('/widgets/:id\.:ext?', requireCurrentShop, setupShopifyApi, async ctx => {
var widget = await Widget.forge({ shop_id: ctx.state.shop.id, id: ctx.params.id }).fetch();
await actions.destroy(Widget, widget, ctx);
ctx.state.shop.syncConfigToShopify();
});
/**
* Show
*/
router.get('/widgets/:id\.:ext?', requireCurrentShop, async ctx => {
var widget = await Widget.forge({ shop_id: ctx.state.shop.id, id: ctx.params.id }).fetch();
var relations = {
account: { id: 'account_id' }
};
await actions.show(Widget, widget, ctx, { serializer, relations });
});
/**
* Index
*/
router.get('/widgets\.:ext?', requireCurrentShop, async ctx => {
var widgets = await Widget.where({ shop_id: ctx.state.shop.id, deleted_at: null }).fetchAll();
var relations = {
shop: { id: 'shop_id' }
};
await actions.index(Widget, widgets, ctx, { serializer, relations });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment