// 默认进程内存级别数据源 curd import { serializeDateTimeLocale } from '@tcwd/weda-utils'; import { IFetchers, Query } from '@tcwd/jsonschema-graphql'; enum MATCH_ACTION { EQUAL = 'equal', NOTQQUAL = 'notEqual', } // 匹配方法 function matchFn(where = {}, action: MATCH_ACTION = MATCH_ACTION.EQUAL) { let fn; switch (action) { case MATCH_ACTION.EQUAL: fn = (item) => Object.keys(where).every((key) => where[key] === item[key]); break; case MATCH_ACTION.NOTQQUAL: fn = (item) => Object.keys(where).every((key) => where[key] !== item[key]); break; } return fn; } function queryList(list, query: Query) { const { where, limit = 20, skip = 0, sort = '' } = query; const [orderField, orderType = 'asc'] = sort.split(':'); let result = list.filter(matchFn(where)); if (orderField) { result = result.sort((x, y) => { if (x[orderField] == y[orderField]) { return 0; } if (orderType.toLowerCase() === 'asc') { return x[orderField] > y[orderField] ? 1 : -1; } return x[orderField] < y[orderField] ? 1 : -1; }); } const total = result.length; result = result.slice(skip, skip + limit); return { list: result, total }; } export function getInlineFetchers(store = {}) { const defaultFetchers: IFetchers = { async getItem(where, { name }) { const list = store[name] || []; return list.find(matchFn(where)); }, async getList(args: Query, { name }) { const list = store[name] || []; return queryList(list, args).list; }, async getRecords(args: Query, { name }) { const { limit = 20, skip = 0, sort = '' } = args; const { list, total } = queryList(store[name] || [], args); return { total, limit, skip, sort, records: list, }; }, async create(data, { name }) { const now = serializeDateTimeLocale(new Date()); const _id = `${Math.round(Math.random() * 1000000)}`; const item = { ...data, _id, createdAt: now, updatedAt: now, }; const list = store[name] || []; list.push(item); if (!store[name]) { store[name] = list; } return { _id, }; }, async delete(where, { name }) { const list = store[name] || []; const newList = list.filter(matchFn(where, MATCH_ACTION.NOTQQUAL)); const deleted = list.length - newList.length; store[name] = newList; return { deleted, }; }, async update({ data, where }, { name }) { const now = serializeDateTimeLocale(new Date()); const list = store[name] || []; const item = list.filter(matchFn(where)); item.forEach((x) => { Object.assign(x, { ...data, updatedAt: now }); }); return { updated: item.length, }; }, }; return { fetchers: defaultFetchers }; }