Skip to content

Commit

Permalink
feat(io): io support crud function, update faas-demo example
Browse files Browse the repository at this point in the history
  • Loading branch information
anran758 committed Mar 20, 2024
1 parent ebfb029 commit d67f377
Show file tree
Hide file tree
Showing 15 changed files with 3,271 additions and 8,508 deletions.
7 changes: 7 additions & 0 deletions apps/faas-demo/mock/channelCreate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
data: {
name: `旧书铺-${new Date()}`,
cover:
'https://cloud-minapp-47549.cloud.ifanrusercontent.com/1rmlh9degSiaF4ua.jpg',
},
};
3 changes: 3 additions & 0 deletions apps/faas-demo/mock/channelDelete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
id: '65fa8a4ae37f7c453e7b7045',
};
30 changes: 30 additions & 0 deletions apps/faas-demo/src/function/channel/channelCreate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { createFaas } from '@mincloudx/faas';
import io from '@/io';

interface EventParams {
data: {
name: string;
cover: string;
};
}

export default createFaas<EventParams>(async function main(event) {
const { data } = event.data;

const record = await io.channel.create(data);
console.log('create result:', record);

const updatedResult = await io.channel.update(record.id, {
data: {
description: 'This is description.',
},
});
console.log('updated result:', updatedResult);

const channel = await io.channel.get(record.id, {
select: ['id', 'name', 'cover', 'description'],
});
console.log('get result:', channel);

return channel;
});
17 changes: 17 additions & 0 deletions apps/faas-demo/src/function/channel/channelDelete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { createFaas } from '@mincloudx/faas';
import io from '@/io';

interface EventParams {
id: string;
}

export default createFaas<EventParams>(async function main(event) {
const { id } = event.data;
// const result = await io.channel.delete(id);

const query = io.getQuery({ id });
const result = await io.channel.delete(query);
console.log('delete result:', result);

return result;
});
5 changes: 5 additions & 0 deletions apps/faas-demo/src/io/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createIo } from '@mincloudx/io';

export default createIo({
tables: ['channel'],
});
4 changes: 2 additions & 2 deletions apps/faas-demo/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"target": "es2022",
"module": "NodeNext",
"target": "ES2015",
"module": "Node16",
"moduleResolution": "node16",
"strict": true,
"esModuleInterop": true,
Expand Down
2 changes: 1 addition & 1 deletion packages/faas/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"moduleResolution": "nodenext",
"outDir": "lib/esm",
"declarationDir": "lib/esm/types",
"rootDir": ".",
"rootDir": "./src",
"baseUrl": "./"
}
}
5 changes: 2 additions & 3 deletions packages/io/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
"license": "MIT",
"private": true,
"main": "dist/main.js",
"typings": "./lib/types/index.d.ts",
"files": [
"dist"
],
"publishConfig": {
"access": "restricted"
},
"scripts": {
"lint": "eslint .",
"test": "jest --verbose",
Expand All @@ -25,6 +23,7 @@
"@mincloudx/baas": "workspace:*",
"@mincloudx/types": "workspace:*",
"@webpack-cli/generators": "^2.5.0",
"terser-webpack-plugin": "^5.3.10",
"ts-loader": "^9.3.1",
"webpack": "^5.74.0",
"webpack-cli": "^5.1.4"
Expand Down
32 changes: 32 additions & 0 deletions packages/io/src/baas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,35 @@ export function getBaaS() {

throw new Error('BaaS is not initialized.');
}

export function getBaseIo(BaaS = getBaaS()) {
return {
get query() {
return new BaaS.Query();
},

get user() {
return new BaaS.User();
},

get file() {
return new BaaS.File();
},

table(tableName: string) {
return new BaaS.TableObject(tableName);
},

getQuery(data?: Record<any, any>) {
const query = new BaaS.Query();
if (!data) return query;

// Provides a completely equivalent way to generate `Query` from passed object letters
Object.entries(data).forEach(([key, value]) => {
query.compare(key, '=', value);
});

return query;
},
};
}
25 changes: 4 additions & 21 deletions packages/io/src/createIo.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,14 @@
import { getBaaS } from './baas';
import { getBaaS, getBaseIo } from './baas';
import { createTableOperation, Operation } from './operations';

export function createIo<T extends string>(options: { tables?: T[] } = {}) {
const BaaS = getBaaS();
const io = getBaseIo(BaaS);

const io = {
get query() {
return new BaaS.Query();
},

get user() {
return new BaaS.User();
},

get file() {
return new BaaS.File();
},

table(tableName: string) {
return new BaaS.TableObject(tableName);
},
};

const dynamicIo: { [K in T]?: Operation } = {};
const dynamicIo = {} as { [K in T]: Operation };
options.tables?.forEach(tableName => {
dynamicIo[tableName] = createTableOperation(tableName);
});

return Object.assign(io, dynamicIo);
return Object.assign(dynamicIo, io);
}
140 changes: 114 additions & 26 deletions packages/io/src/operations.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,70 @@
import { getBaaS } from './baas';
import { BaaS } from '@mincloudx/types';
import { getBaaS, getBaseIo } from './baas';

// export type RemoveFirst<T extends any[]> = T extends [any, ...infer Rest]
// ? Rest
// : never;

// export type OmitFirstParamFunction<F extends (...args: any) => any> = (
// ...args: RemoveFirst<Parameters<F>>
// ) => ReturnType<F>;
type RecordId = string | number;

interface BasicOperationOptions {
plain?: boolean;
}

type RecordId = string | number;
interface UpdateOperationOptions extends BasicOperationOptions {
data?: Record<string | number, any>;
unset?: Record<string | number, any>;
incrementBy?: Record<string | number, any>;
append?: Record<string | number, any>;
uAppend?: Record<string | number, any>;
remove?: Record<string | number, any>;
patchObject?: Record<string | number, any>;
enableTrigger?: boolean;
withCount?: boolean;
}

interface QueryOperationOptions extends BasicOperationOptions {
expand?: string[];
select?: string[];
}

interface DeleteOperation {
id?: RecordId;
query?: BaaS.Query;
offset?: number;
limit?: number;
enableTrigger?: boolean;
withCount?: boolean;
}

export interface Operation {
readonly table: any;
create: <T extends object = Record<any, any>>(
data: T,
options?: BasicOperationOptions,
) => Promise<Record<any, any>>;
update: <T extends object = Record<any, any>>(
id: RecordId,
data: T,
options?: BasicOperationOptions,
) => Promise<Record<any, any>>;
get: (
id: RecordId,
options?: BasicOperationOptions,
options?: QueryOperationOptions,
) => Promise<Record<any, any>>;
delete: (id: RecordId) => Promise<any>;
update: <T extends object = Record<any, any>>(
id: RecordId,
options: UpdateOperationOptions,
) => Promise<T>;
delete: (
query: DeleteOperation['id'] | DeleteOperation['query'],
) => Promise<any>;
}

const io = getBaseIo();

export function createTableOperation(tableName: string) {
const BaaS = getBaaS();
const tableOperation: Operation = {
get table() {
return new BaaS.TableObject(tableName);
},

async create(data, { plain } = {}) {
/**
* Create new a row for the table
*/
async create(data, { plain = true } = {}) {
const record = tableOperation.table.create();

return record
Expand All @@ -48,24 +73,87 @@ export function createTableOperation(tableName: string) {
.then(res => (plain ? res.data : res));
},

async update(id, data) {
console.log(`Updating record ${id} in ${tableName} with data:`, data);
async update(
id,
{
data,
unset,
incrementBy,
append,
uAppend,
remove,
patchObject,
withCount = false,
enableTrigger = true,
plain = true,
} = {},
) {
if (!id) {
throw new Error('Missing required id parameter');
}
const record = tableOperation.table.getWithoutData(id);
const mergeOperator = (method, data) =>
Object.entries(data).forEach(([key, val]) => record[method](key, val));

if (data) mergeOperator('set', data);
if (unset) mergeOperator('unset', unset);
if (incrementBy) mergeOperator('incrementBy', incrementBy);
if (append) mergeOperator('append', append);
if (uAppend) mergeOperator('uAppend', uAppend);
if (remove) mergeOperator('remove', remove);
if (patchObject) mergeOperator('patchObject', patchObject);

return Promise.resolve(data);
return record
.update({ enableTrigger, withCount })
.then(res => (plain ? res.data : res));
},

async get(id) {
console.log(`Creating record in ${tableName} with data`, id);
async get(id, { expand, select, plain = true } = {}) {
const { table } = tableOperation;
if (expand) table.expand(expand);
if (select) table.select(select);

return {};
return table.get(id).then(res => (plain ? res.data : res));
},

async delete(id) {
console.log(`Deleting record ${id} from ${tableName}`);
async delete(query, options: Omit<DeleteOperation, 'id' | 'query'> = {}) {
if (!query) {
return Promise.reject(new Error('Missing required id parameter'));
}
const opts: DeleteOperation = {
...options,
};
if (typeof query === 'string' || typeof query === 'number') {
opts.id = query;
} else {
opts.query = query;
}

return {};
return deleteRecord(tableOperation.table, opts);
},
};

return tableOperation;
}

/**
* delete data record
*/
function deleteRecord(
table,
{
id,
query = io.query,
offset = 0,
limit,
enableTrigger = true,
withCount = false,
}: DeleteOperation = {},
) {
if (query) {
table.offset(offset);
if (limit) table.limit(limit);
}

return table.delete(id || query, { enableTrigger, withCount });
}
10 changes: 5 additions & 5 deletions packages/io/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
"./types"
],
"noImplicitAny": false,
"target": "es2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "es2015",
"module": "Node16",
"moduleResolution": "Node16",
"lib": ["es2015"],
"declarationDir": "lib/types",
"outDir": "lib",
"rootDir": ".",
"baseUrl": "./src"
"rootDir": "./src",
"baseUrl": "."
}
}
Loading

0 comments on commit d67f377

Please sign in to comment.