From 8f0a71a1cffd1389d8000d11055a05d4b3f97f85 Mon Sep 17 00:00:00 2001 From: Chareice Date: Thu, 16 Dec 2021 10:58:51 +0800 Subject: [PATCH] feat: collection autoGenId option --- .../database/src/__tests__/collection.test.ts | 15 +++++++++++++++ packages/database/src/collection.ts | 8 +++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/database/src/__tests__/collection.test.ts b/packages/database/src/__tests__/collection.test.ts index be1d8df28..df1f2c399 100644 --- a/packages/database/src/__tests__/collection.test.ts +++ b/packages/database/src/__tests__/collection.test.ts @@ -2,6 +2,21 @@ import { generatePrefixByPath, mockDatabase } from './index'; import { Collection } from '../collection'; import { Database } from '../database'; +test('collection disable authGenId', async () => { + const db = mockDatabase(); + + const Test = db.collection({ + name: 'test', + autoGenId: false, + fields: [{ type: 'string', name: 'uid', primaryKey: true }], + }); + + const model = Test.model; + + await db.sync(); + expect(model.rawAttributes['id']).toBeUndefined(); +}); + test('new collection', async () => { const db = mockDatabase(); const collection = new Collection( diff --git a/packages/database/src/collection.ts b/packages/database/src/collection.ts index a91604eff..62fffb4b1 100644 --- a/packages/database/src/collection.ts +++ b/packages/database/src/collection.ts @@ -18,6 +18,7 @@ export interface CollectionOptions extends Omit { fields?: FieldOptions[]; model?: string | ModelCtor; repository?: string | RepositoryType; + autoGenId?: boolean; [key: string]: any; } @@ -67,7 +68,7 @@ export class Collection< if (this.model) { return; } - const { name, model } = this.options; + const { name, model, autoGenId = true } = this.options; let M = Model; if (this.context.database.sequelize.isDefined(name)) { const m = this.context.database.sequelize.model(name); @@ -84,6 +85,11 @@ export class Collection< } this.model = class extends M {}; this.model.init(null, this.sequelizeModelOptions()); + + if (!autoGenId) { + this.model.removeAttribute('id'); + } + Object.defineProperty(this.model, 'database', { value: this.context.database }); }