const pg = require('../pg') const joinjs = require('join-js').default; const debug = require('debug')('sos:db:item') const mappings = require('../mappings') const sharp = require('sharp') const item = module.exports = {} item.findAll = async () => { const query = 'select * from sos.v_item' debug(query); const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_'); } item.findById = async (item_uuid) => { const query = { text: 'select * from sos.v_item where item_uuid = $1', values: [ item_uuid ] } debug(query); const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0]; } item.findBySlug = async (item_slug) => { const query = { text: 'select * from sos.v_item where item_urlslug = $1', values: [ item_slug ] } debug(query); const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0]; } item.create = async (name, urlslug, description, price_cents, published) => { const query = { text: 'select * from sos.create_item($1::text, $2::citext, $3::text, $4::integer, $5::boolean)', values: [ name, urlslug, description, price_cents, published ] } debug(query) const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0] } item.addImage = async (item_uuid, image_buffer, uploader_uuid) => { // Default param chain: output as png const source = sharp(image_buffer).png() // All output images clone the source param chain, and then // resize before creating a buffer const [image, thumb] = await Promise.all([ source.clone().toBuffer(), source.clone().resize({width: 300}).toBuffer() ]) const query = { text: 'select * from sos.add_image_to_item($1, $2, $3, $4, $5)', values: [ item_uuid, image, thumb, 'image/png', uploader_uuid ] } const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0] } const imageSizeQueries = { 'large': 'select * from sos.get_image_large($1)', 'thumb': 'select * from sos.get_image_thumb($1)' } item.getImage = async (image_uuid, size) => { if(!imageSizeQueries[size]) throw new Error(`Cannot get unknown image size: "${size}"`) const query = { text: imageSizeQueries[size], values: [image_uuid] } const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'bareImageMap', 'image_')[0]; } item.removeImage = async (image_uuid) => { const query = { text: 'select * from sos.delete_image($1)', values: [ image_uuid ] } const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0] } item.removeItem = async (item_uuid) => { const query = { text: 'select * from sos.delete_item($1)', values: [ item_uuid ] } const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'itemMap', 'item_')[0] }