// 使用基础云开发 node-sdk 实现的内置数据源方法 // 可做测试用 import * as tcb from '@cloudbase/node-sdk'; import { serializeDateTimeLocale } from '@tcwd/weda-utils'; import { IFetchers, Query } from '@tcwd/jsonschema-graphql'; import { FlexDBOption } from '../types'; export function getTCBNodeFetchers(opts: FlexDBOption = {}) { const tcbApp = tcb.init({ env: opts.envId || tcb.SYMBOL_CURRENT_ENV, proxy: opts.proxy || process.env.HTTP_PROXY, }); const db = tcbApp.database(); function getCollectionName(datasrouce) { const { name, id } = datasrouce; return `lcap-${id}-${name}${process.env.IS_PREVIEW ? '-preview' : ''}`; } // query async function collQuery(query: Query, jsonschema) { const collection = db.collection(getCollectionName(jsonschema)); const { where, limit = 20, skip, sort = '' } = query; let exp; const [orderField, orderType = 'asc'] = sort.split(':'); if (where) { exp = collection.where(where); } else { exp = collection; } exp = exp.limit(limit); if (skip) { exp = exp.skip(skip); } if (orderField) { exp = exp.orderBy(orderField, orderType.toLowerCase()); } const res = await exp.get(); return res; } // count async function collCount(where, jsonschema) { const collection = db.collection(getCollectionName(jsonschema)); let exp; if (where) { exp = collection.where(where); } else { exp = collection; } const res = await exp.count(); return res.total; } const fetchers: IFetchers = { async getItem(where, jsonschema) { let res; const coll = db.collection(getCollectionName(jsonschema)); if (Object.keys(where).length === 1 && where._id) { res = await coll.doc(where._id).get(); } else { res = await coll.where(where).limit(1).get(); } return res.data[0]; }, async getList(args: Query, jsonschema) { const res = await collQuery(args, jsonschema); return res.data; }, async getRecords(args: Query, jsonschema) { const { where, limit, skip, sort } = args; const [records, total] = await Promise.all([ collQuery(args, jsonschema).then((r) => r.data), collCount(where, jsonschema), ]); return { total, limit, skip, sort, records, }; }, async create(data, jsonschema) { const now = serializeDateTimeLocale(new Date()); const item = { ...data, createdAt: now, updatedAt: now, }; const res = await db.collection(getCollectionName(jsonschema)).add(item); return { _id: res.id, requestId: res.requestId, }; }, async delete(where, jsonschema) { const res = await db.collection(getCollectionName(jsonschema)).where(where).remove(); return { deleted: res.deleted ? (res.deleted as number) * 1 : 0, requestId: res.requestId, }; }, async update({ data, where }, jsonschema) { const now = serializeDateTimeLocale(new Date()); const item = { ...data, updatedAt: now, }; return db.collection(getCollectionName(jsonschema)).where(where).update(item); }, }; return { app: tcbApp, database: db, fetchers, getCollectionName, }; }