Skip to content

Commit 720160e

Browse files
authored
Merge pull request #39 from DouglasNeuroInformatics/dev
feat: add ValidObjectIdPipe
2 parents b786959 + 3e756eb commit 720160e

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export type { VirtualizationModuleOptions } from './modules/virtualization/virtu
4040
export { VirtualizationModule } from './modules/virtualization/virtualization.module.js';
4141
export { VirtualizationService } from './modules/virtualization/virtualization.service.js';
4242
export { ParseSchemaPipe } from './pipes/parse-schema.pipe.js';
43+
export { ValidObjectIdPipe } from './pipes/valid-object-id.pipe.js';
4344
export { $BaseEnv } from './schemas/env.schema.js';
4445
export type { BaseEnv } from './schemas/env.schema.js';
4546
export type { BaseEnvSchema } from './utils/env.utils.js';
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { BadRequestException } from '@nestjs/common';
2+
import { ObjectId } from 'mongodb';
3+
import { describe, expect, it } from 'vitest';
4+
5+
import { ValidObjectIdPipe } from '../valid-object-id.pipe.js';
6+
7+
describe('ValidObjectIdPipe', () => {
8+
it('should return the input value if it is a valid object id', () => {
9+
const pipe = new ValidObjectIdPipe();
10+
const value = new ObjectId().toString();
11+
expect(pipe.transform(value)).toEqual(value);
12+
});
13+
it('should throw BadRequestException if validation fails', () => {
14+
const pipe = new ValidObjectIdPipe();
15+
const value = crypto.randomUUID();
16+
expect(() => pipe.transform(value)).toThrow(BadRequestException);
17+
});
18+
});

src/pipes/valid-object-id.pipe.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { BadRequestException, Injectable } from '@nestjs/common';
2+
import type { PipeTransform } from '@nestjs/common';
3+
import { ObjectId } from 'mongodb';
4+
5+
@Injectable()
6+
export class ValidObjectIdPipe implements PipeTransform<string> {
7+
transform(value: unknown): string {
8+
if (!(typeof value === 'string' && ObjectId.isValid(value))) {
9+
throw new BadRequestException(`Invalid ObjectID: ${String(value)}`);
10+
}
11+
return value;
12+
}
13+
}

0 commit comments

Comments
 (0)