import { IFetchers } from '@tcwd/jsonschema-graphql'; import { callBuiltinMethod, getFnContext } from '@cloudbase/weda-node-sdk'; import { EJSON } from 'bson'; async function callBuiltinFlexDB(methodName, args, jsonschema, context) { const { scfContext } = context; const res = await callBuiltinMethod( { methodName, dataSourceName: jsonschema.name, params: args, }, getFnContext({ rawContext: scfContext, params: { methodName, params: args, envType: process.env.IS_PREVIEW ? 'pre' : 'prod', proxy: process.env.proxy, }, }), ); return EJSON.parse(JSON.stringify(res.data)); } function queryTransition(query) { const { where = {}, limit = 20, skip = 0, sort = '' } = query; const [orderBy, orderType = 'asc'] = sort.split(':'); const someWhere = Object.keys(where).map((key) => { return { key: key, rel: 'eq', val: where[key], }; }); return { pageNo: Math.floor(skip / limit) + 1, pageSize: limit, orderBy, orderType, where: someWhere, }; } const fetchers: IFetchers = { async getItem(args, jsonschema, { context }) { return callBuiltinFlexDB('getItem', args, jsonschema, context); }, // getList 入参能力为对其 getRecords async getList({ where }, jsonschema, { context }) { return callBuiltinFlexDB('getList', where, jsonschema, context) as Promise; }, async getRecords(args, jsonschema, { context }) { const res: any = await callBuiltinFlexDB('getRecords', queryTransition(args), jsonschema, context); return { total: res.total, records: res.records, limit: res.pageSize, skip: res.pageSize * (res.pageNo - 1), sort: args.sort, }; }, async create(data, jsonschema, { context }) { const res = (await callBuiltinFlexDB('create', data, jsonschema, context)) as any; return { _id: res._id, requestId: res.requestId, }; }, async delete(where, jsonschema, { context }) { return callBuiltinFlexDB('delete', where, jsonschema, context) as any; }, async update({ where, data }, jsonschema, { context }) { return callBuiltinFlexDB('update', { ...data, _id: (where as any)._id }, jsonschema, context) as any; }, }; export function getWedaDefaultFetchers(opts?) { return { fetchers, }; }