Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: optionally allow validatorOptions of class-validator #233

Merged
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/AbstractFirestoreRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ export abstract class AbstractFirestoreRepository<T extends IEntity> extends Bas
*/
const entity = item instanceof Entity ? item : Object.assign(new Entity(), item);

return classValidator.validate(entity);
return classValidator.validate(entity, this.config.validatorOptions);
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
throw new Error(
Expand Down
34 changes: 34 additions & 0 deletions src/BaseFirestoreRepository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,40 @@ describe('BaseFirestoreRepository', () => {
expect(band.contactEmail).toEqual('Not an email');
});


it('must not validate forbidden non-whitelisted properties if the validatorOptions: {}', async () => {
initialize(firestore, { validateModels: true, validatorOptions: {} });

bandRepository = new BandRepository('bands');

let entity = new Band();
entity = {
...entity,
unknownProperty: 'unknown property'
} as unknown as Band;
const band = await bandRepository.create(entity);

expect((band as any).unknownProperty).toEqual('unknown property');
});

it('must validate forbidden non-whitelisted properties if the validatorOptions: { whitelist: true, forbidNonWhitelisted: true }', async () => {
initialize(firestore, { validateModels: true, validatorOptions: { whitelist: true, forbidNonWhitelisted: true } });

bandRepository = new BandRepository('bands');

let entity = new Band();
entity = {
...entity,
unknownProperty: 'unknown property'
} as unknown as Band;

try {
await bandRepository.create(entity);
} catch (error) {
expect(error[0].constraints.whitelistValidation).toEqual('property unknownProperty should not exist');
}
});

it('must fail validation if an invalid class is given', async () => {
initialize(firestore, { validateModels: true });

Expand Down
37 changes: 37 additions & 0 deletions src/Batch/BaseFirestoreBatchRepository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,43 @@ describe('BaseFirestoreBatchRepository', () => {
validationBandRepository.delete(entity);
expect(validationBatch.commit).not.toThrow();
});

it('must not validate forbidden non-whitelisted properties if the validatorOptions: {}', async () => {
initialize(firestore, { validateModels: true, validatorOptions: {} });

const validationBatch = new FirestoreBatchUnit(firestore);
const validationBandRepository = new BaseFirestoreBatchRepository(Band, validationBatch);

let entity = new Band();
entity = {
...entity,
unknownProperty: 'unknown property'
} as unknown as Band;

validationBandRepository.create(entity);
expect(validationBatch.commit).not.toThrow();
});

it('must validate forbidden non-whitelisted properties if the validatorOptions: {whitelist: true, forbidNonWhitelisted: true}', async () => {
initialize(firestore, { validateModels: true, validatorOptions: { whitelist: true, forbidNonWhitelisted: true } });

const validationBatch = new FirestoreBatchUnit(firestore);
const validationBandRepository = new BaseFirestoreBatchRepository(Band, validationBatch);

let entity = new Band();
entity = {
...entity,
unknownProperty: 'unknown property'
} as unknown as Band;

validationBandRepository.create(entity);

try {
await validationBatch.commit();
} catch (error) {
expect(error[0].constraints.whitelistValidation).toEqual('property unknownProperty should not exist');
}
});
});

// eslint-disable-next-line @typescript-eslint/no-empty-function
Expand Down
2 changes: 1 addition & 1 deletion src/Batch/BaseFirestoreBatchRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class BaseFirestoreBatchRepository<T extends IEntity> implements IBatchRe
item.id = doc.id;
}

this.batch.add('create', item as T, doc, this.colMetadata, this.config.validateModels);
this.batch.add('create', item as T, doc, this.colMetadata, this.config.validateModels, this.config.validatorOptions);
};

update = (item: T) => {
Expand Down
12 changes: 8 additions & 4 deletions src/Batch/FirestoreBatchUnit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { Firestore, DocumentReference } from '@google-cloud/firestore';
import { FullCollectionMetadata } from '../MetadataStorage';
import { serializeEntity } from '../utils';
import { ValidationError } from '../Errors/ValidationError';
import { ValidatorOptions } from 'class-validator';

type BatchOperation<T extends IEntity> = {
type: 'create' | 'update' | 'delete';
item: IEntity;
ref: DocumentReference;
collectionMetadata: FullCollectionMetadata;
validateModels: boolean;
validatorOptions?: ValidatorOptions
};

export class FirestoreBatchUnit {
Expand All @@ -23,14 +25,16 @@ export class FirestoreBatchUnit {
item: T,
ref: DocumentReference,
collectionMetadata: FullCollectionMetadata,
validateModels: boolean
validateModels: boolean,
validatorOptions?: ValidatorOptions
) {
this.operations.push({
type,
item,
ref,
collectionMetadata,
validateModels,
validatorOptions
});
}

Expand All @@ -48,7 +52,7 @@ export class FirestoreBatchUnit {

for (const op of this.operations) {
if (op.validateModels && ['create', 'update'].includes(op.type)) {
const errors = await this.validate(op.item, op.collectionMetadata.entityConstructor);
const errors = await this.validate(op.item, op.collectionMetadata.entityConstructor, op.validatorOptions);

if (errors.length) {
throw errors;
Expand Down Expand Up @@ -77,7 +81,7 @@ export class FirestoreBatchUnit {
return result;
};

async validate(item: IEntity, Entity: Constructor<IEntity>): Promise<ValidationError[]> {
async validate(item: IEntity, Entity: Constructor<IEntity>, validatorOptions?: ValidatorOptions): Promise<ValidationError[]> {
try {
const classValidator = await import('class-validator');

Expand All @@ -86,7 +90,7 @@ export class FirestoreBatchUnit {
*/
const entity = item instanceof Entity ? item : Object.assign(new Entity(), item);

return classValidator.validate(entity);
return classValidator.validate(entity, validatorOptions);
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
throw new Error(
Expand Down
3 changes: 3 additions & 0 deletions src/MetadataStorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Firestore } from '@google-cloud/firestore';
import { ValidatorOptions } from 'class-validator';
import { BaseRepository } from './BaseRepository';
import { IEntityConstructor, Constructor, IEntity, IEntityRepositoryConstructor } from './types';
import { arraysAreEqual } from './utils';
Expand Down Expand Up @@ -32,6 +33,7 @@ export interface RepositoryMetadata {

export interface MetadataStorageConfig {
validateModels: boolean;
validatorOptions?: ValidatorOptions;
}

export class MetadataStorage {
Expand All @@ -40,6 +42,7 @@ export class MetadataStorage {

public config: MetadataStorageConfig = {
validateModels: false,
validatorOptions: {}
};

public getCollection = (pathOrConstructor: string | IEntityConstructor) => {
Expand Down
2 changes: 1 addition & 1 deletion src/MetadataUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const getMetadataStorage = (): MetadataStorage => {

export const initialize = (
firestore: Firestore,
config: MetadataStorageConfig = { validateModels: false }
config: MetadataStorageConfig = { validateModels: false, validatorOptions: {} }
): void => {
initializeMetadataStorage();

Expand Down