UNPKG

@gameroom/cli

Version:

A command line tool for Gameroom

59 lines (56 loc) 2.33 kB
const cosmetic = require('cosmetic'), { models: { Price } } = require('@gameroom/kit'), { tryRepeatedly } = require('../../helpers'), { shopify, spinner } = require('../../refs') const whitelist = [ { key: 'genre', type: 'single_line_text_field' }, { key: 'platform', type: 'single_line_text_field' }, { key: 'release_date', type: 'date' } ] module.exports = class Metafield { constructor(data) { if (!data) data = {} this.created_at = data.created_at this.updated_at = data.updated_at this.description = data.description this.id = data.id this.key = data.key this.namespace = data.namespace this.owner_id = data.owner_id this.owner_resource = data.owner_resource this.value = data.value this.type = data.type } static async forProduct(product) { const result = await tryRepeatedly(() => shopify.get(`/products/${product.id}/metafields.json`, { params: { limit, since_id: products.length > 0 ? products[products.length - 1].id : 0 }, })) const metafields = result && result.data && result.data.products ? result.data.products : [] const metafields = result && result.data && result.data.products ? result.data.products : [] return products.reduce((a, i) => [...a, new Product(i)], []) } static async fromProduct(product) { return whitelist.reduce((a, { description, key, namespace, type }) => !product.properties[key] ? a : [...a, new Metafield({ description, key, namespace, owner_id: product.properties.shopify_id, owner_resource: 'product', value: product.properties[key], type }) ] }, []) } clean() { return Object.keys(this).reduce((a, i) => this[i] === undefined ? a : { ...a, [i]: this[i] }, {}) } async save() { const result = await tryRepeatedly(() => shopify.post(`/metafields.json`, { metafield: this.clean() }), (err) => spinner.warn(`error saving ${cosmetic.green('shopify metafield')} ${err}`)) return result && result.data && result.data.metafield ? new Metafield(result.data.metafield) : null } async delete() { const result = await tryRepeatedly(() => shopify.delete(`/metafields/${this.id}.json`), (err) => spinner.warn(`error deleting ${cosmetic.green('shopify metafield')} ${id} ${err}`)) return result } }