const models = require('../models'); const { Op } = require("sequelize"); import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; const getSequelizeWhere = (queryElem: api.SongQueryElem) => { var and = []; var sequelizeOps:any = {}; sequelizeOps[api.SongQueryFilterOp.Eq] = Op.eq; sequelizeOps[api.SongQueryFilterOp.Ne] = Op.ne; sequelizeOps[api.SongQueryFilterOp.In] = Op.in; sequelizeOps[api.SongQueryFilterOp.NotIn] = Op.notIn; sequelizeOps[api.SongQueryElemOp.And] = Op.and; sequelizeOps[api.SongQueryElemOp.Or] = Op.or; var sequelizeProps:any = {}; sequelizeProps[api.SongQueryElemProperty.id] = "id"; sequelizeProps[api.SongQueryElemProperty.artistIds] = "artistIds"; sequelizeProps[api.SongQueryElemProperty.albumIds] = "albumIds"; if (queryElem.prop && queryElem.propOperator && queryElem.propOperand) { const prop = sequelizeProps[queryElem.prop]; const op = sequelizeOps[queryElem.propOperator]; var filter:any = {}; filter[op] = queryElem.propOperand; var where:any = {}; where[prop] = filter; and.push(where); } if (queryElem.childrenOperator && queryElem.children) { const children = queryElem.children.map((child: api.SongQueryElem) => getSequelizeWhere(child)); const op = sequelizeOps[queryElem.childrenOperator]; var where:any = {}; where[op] = children; and.push(where) } return { [Op.and]: and }; } export const QuerySongsEndpointHandler: EndpointHandler = async (req: any, res: any) => { if (!api.checkQuerySongsRequest(req)) { const e: EndpointError = { internalMessage: 'Invalid QuerySongs request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } const reqObject: api.QuerySongsRequest = req.body; await models.Song.findAll({ where: getSequelizeWhere(reqObject.query) }) .then((songs: any[]) => { const response: api.QuerySongsResponse = { ids: songs.map((song: any) => { return song.id; }) }; res.send(response); }) .catch(catchUnhandledErrors); }