Can apollo-upload file be optional? NestJS code-first approach - nestjs

I have an upload funtion using apollo-upload, and I want to validate if the file is provided in the request or not, but I'm messing around and can't find any solution.
I have a Mutation like below:
async someFn(
#Args({ name: 'file', type: () => GraphQLUpload })
{ createReadStream, filename }: FileUpload
)
If the file was not provided, the server return INTERNAL_SERVER_ERROR that I didn't want to.
"extensions": {
"code": "INTERNAL_SERVER_ERROR"
}
I tried validate the file inside the resolvers but it not working, maybe because the FileUpload path is required. I still can't figure out is there any way that I can catch the error when the file is empty?
UPDATE: just wrap input into InputType class and we easy to customize input type and the interface
export class MyInput {
#Field(() => GraphQLUpload, { nullable: true})
file?: FileUpload;
}
-----
export interface FileUpload {
filename: string;
mimetype: string;
encoding: string;
createReadStream: () => Stream;
}
-----
#Args('payload', { nullable: true }), payload: MyInput)

Related

How to use data from DB as initial state with Zustand

I'm using the T3 stack (TypeScript, tRPC, Prisma, Next, etc) and I want to either load data from my database using a tRPC query, or use an empty array in my Zustand store. I keep getting an error saying:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
and fix this problem. error - TypeError: Cannot read properties of
null (reading 'useContext')
(node:internal/process/task_queues:96:5) { page: '/' }
here's the code generating the error:
type Image = {
url: string;
prompt: string;
};
interface UserState {
images: Image[] | [];
isLoading: boolean;
addImage: (url: string, prompt: string) => void;
removeImage: (url: string, prompt: string) => void;
setLoading: () => void;
}
export const useStore = create<UserState>((set) => {
const { data: sessionData } = useSession();
const dbImages = trpc.images.list.useQuery({
limit: 20,
userId: sessionData?.user?.id ?? "",
}).data?.items;
return {
// initial state
images: dbImages ? dbImages : [],
isLoading: false,
// methods for manipulating state
addImage: (url, prompt) => {
set((state) => ({
images: [
...state.images,
{
url: url,
prompt: prompt,
} as Image,
],
}));
},
removeImage: (url: string) => {
set((state) => ({
images: state.images?.filter((x) => x.url !== url),
}));
},
setLoading: () => {
set((state) => ({
isLoading: !state.isLoading,
}));
},
};
});
What am I doing wrong here? I'm still in the learning phases and would appreciate best practices, etc.

Class-Validator (Node.js) Get another property value within custom validation

At the moment, I have a very simple class-validator file with a ValidationPipe in Nest.js as follows:
import {
IsDateString,
IsEmail,
IsOptional,
IsString,
Length,
Max,
} from 'class-validator';
export class UpdateUserDto {
#IsString()
id: string;
#Length(2, 50)
#IsString()
firstName: string;
#IsOptional()
#Length(2, 50)
#IsString()
middleName?: string;
#Length(2, 50)
#IsString()
lastName: string;
#IsEmail()
#Max(255)
email: string;
#Length(8, 50)
password: string;
#IsDateString()
dateOfBirth: string | Date;
}
Lets say in the above "UpdateUserDto," the user passes an "email" field. I want to build a custom validation rule through class-validator such that:
Check if email address is already taken by a user from the DB
If the email address is already in use, check if the current user (using the value of 'id' property) is using it, if so, validation passes, otherwise, if it is already in use by another user, the validation fails.
While checking if the email address is already in use is a pretty simple task, how would you be able to pass the values of other properties within the DTO to a custom decorator #IsEmailUsed
It was pretty simple to solve, I solved it by creating a custom class-validation Decorator as below:
import { PrismaService } from '../../prisma/prisma.service';
import {
registerDecorator,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { Injectable } from '#nestjs/common';
#ValidatorConstraint({ name: 'Unique', async: true })
#Injectable()
export class UniqueConstraint implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: any, args: ValidationArguments): Promise<boolean> {
const [model, property = 'id', exceptField = null] = args.constraints;
if (!value || !model) return false;
const record = await this.prisma[model].findUnique({
where: {
[property]: value,
},
});
if (record === null) return true;
if (!exceptField) return false;
const exceptFieldValue = (args.object as any)[exceptField];
if (!exceptFieldValue) return false;
return record[exceptField] === exceptFieldValue;
}
defaultMessage(args: ValidationArguments) {
return `${args.property} entered is not valid`;
}
}
export function Unique(
model: string,
uniqueField: string,
exceptField: string = null,
validationOptions?: ValidationOptions,
) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [model, uniqueField, exceptField],
validator: UniqueConstraint,
});
};
}
However, to allow DI to that particular Decorator, you need to also add this to your main.ts bootstrap function:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
// Line below needs to be added.
useContainer(app.select(AppModule), { fallbackOnErrors: true });
...
}
Also, make sure to import the "Constraint" in the app module:
#Module({
imports: ...,
controllers: [AppController],
providers: [
AppService,
PrismaService,
...,
// Line below added
UniqueConstraint,
],
})
export class AppModule {}
Finally, add it to your DTO as such:
export class UpdateUserDto {
#IsString()
id: string;
#IsEmail()
#Unique('user', 'email', 'id') // Adding this will check in the user table for a user with email entered, if it is already taken, it will check if it is taken by the same current user, and if so, no issues with validation, otherwise, validation fails.
email: string;
}
Luckily for us, the class-validator provides a very handy useContainer function, which allows setting the container to be used by the class-validor library.
So add this code in your main.ts file (app variable is your Nest application instance):
useContainer(app.select(AppModule), { fallbackOnErrors: true });
It allows the class-validator to use the NestJS dependency injection container.
#ValidatorConstraint({ name: 'emailId', async: true })
#Injectable()
export class CustomEmailvalidation implements ValidatorConstraintInterface {
constructor(private readonly prisma: PrismaService) {}
async validate(value: string, args: ValidationArguments): Promise<boolean> {
return this.prisma.user
.findMany({ where: { email: value } })
.then((user) => {
if (user) return false;
return true;
});
}
defaultMessage(args: ValidationArguments) {
return `Email already exist`;
}
}
Don't forget to declare your injectable classes as providers in the appropriate module.
Now you can use your custom validation constraint. Simply decorate the class property with #Validate(CustomEmailValidation) decorator:
export class CreateUserDto {
#Validate(customEmailValidation)
email: string;
name: string;
mobile: number;
}
If the email already exists in the database, you should get an error with the default message "Email already exists". Although using #Validate() is fine enough, you can write your own decorator, which will be much more convenient. Having written Validator Constraint is quick and easy. We need to just write decorator factory with registerDecorator() function.
export function Unique(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: CustomEmailvalidation,
});
};
}
As you can see, you can either write new validator logic or use written before validator constraint (in our case - Unique class).
Now we can go back to our User class and use the #Unique validator instead of the #Validate(CustomEmailValidation) decorator.
export class CreateUserDto {
#Unique()
email: string;
name: string;
mobile: number;
}
I think your first use case (Check if email address is already taken by a user from the DB), can be solved by using custom-validator
For the second one there is no option to get the current user before the validation. Suppose you are getting the current user using the #CurrentUser decorator. Then once the normal dto validation is done, you need to check inside the controller or service if the current user is accessing your resource.

Class-Transformer: access request object or pass in additional metadata?

I need to transform some file URL's in the response, the file paths need to contain the client id,
I have a shared class 'AssetReponseImagesDTO' this is used in lots of other classes, I need to transform the value of filename from a local path to append the CDN URL and client id and return a proper URL
I can get the CDN URL from the configService as it's just a string, to get the value of ClientId i have a custom decorator for nest.js - tried to use this decorator to access the same Id within the response but it doesn't work - seems to just return a string of the actual function
I also tried to create a new ClientId property on my top-level response DTO however the lower level Type such as AssetResponseImagesDTO won't have access to the parent's properties (unless I'm mistaken?)
Is there a way to pass in additional information to class-transformer which can then be referenced during the transform process?
export class AssetResponseImagesDTO {
#Expose({ name: 'url' })
#Transform(({ value }) =>
value ? `${configService.getCDNUrl()}${NEED_CLIENT_ID_HERE}}/asset/${value}` : null,
)
filename: string;
#Expose()
caption: string;
#Expose({ name: 'link' })
url: string;
}
Updated for more detail
Top-level response DTO
export class NewVehicleDetailResponseWrapperDTO {
#Type(() => NewVehicleResponseDTO)
vehicle: NewVehicle;
#Type(() => AssetResponseDTO)
assets: Asset[];
constructor(vehicle, assets) {
this.vehicle = vehicle;
this.assets = assets;
}
}
AssetResponseDTO
#Exclude()
export class AssetResponseDTO {
#Expose({ name: 'type' })
#Transform(({ value }) => AssetType[value])
assetType: AssetType;
#Expose({ name: 'name' })
scrapName: string;
#Expose({ name: 'images' })
#Type(() => AssetResponseImagesDTO)
assetImages: AssetImages[];
#Expose({ name: 'snippet' })
#Transform(({ value }) => value?.snippet)
#Type(() => AssetSnippets)
assetSnippet: AssetSnippets;
#Expose({ name: 'content' })
#Transform(({ value }) => value?.article)
#Type(() => AssetContents)
assetContent: AssetContents;
}
ClientId Decorator
export const ClientId = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
// We need to set the clientId either via a query param or from the logged in user.
let clientId;
if (request.user.clientId) {
clientId = request.user.clientId;
}
if (request.headers['x-client-id']) {
clientId = request.headers['x-client-id'];
}
if (!clientId) {
throw new BadRequestException();
}
return clientId;
},
);

How to test Validation pipe is throwing the expect error for improperly shaped request on NestJS

I'm using NestJS 7.0.2 and have globally enabled validation pipes via app.useGlobalPipes(new ValidationPipe());.
I'd like to be able to have a unit test that verifies that errors are being thrown if the improperly shaped object is provided, however the test as written still passes. I've seen that one solution is to do this testing in e2e via this post, but I'm wondering if there is anything I'm missing that would allow me to do this in unit testing.
I have a very simple controller with a very simple DTO.
Controller
async myApi(#Body() myInput: myDto): Promise<myDto | any> {
return {};
}
DTO
export class myDto {
#IsNotEmpty()
a: string;
#IsNotEmpty()
b: string | Array<string>
}
Spec file
describe('generate', () => {
it('should require the proper type', async () => {
const result = await controller.generate(<myDto>{});
// TODO: I expect a validation error to occur here so I can test against it.
expect(result).toEqual({})
})
})
It also fails if I do not coerce the type of myDto and just do a ts-ignore on a generic object.
Just test your DTO with ValidationPipe:
it('validate DTO', async() => {
let target: ValidationPipe = new ValidationPipe({ transform: true, whitelist: true });
const metadata: ArgumentMetadata = {
type: 'body',
metatype: myDto,
data: ''
};
await target.transform(<myDto>{}, metadata)
.catch(err => {
expect(err.getResponse().message).toEqual(["your validation error"])
})
});
You can find here complete test examples for ValidationPipe in Nestjs code repository
To test custom ValidationPipe:
let target = new ValidationDob();
const metadata: ArgumentMetadata = {
type: 'query',
metatype: GetAgeDto,
data: '',
};
it('should throw error when dob is invalid', async () => {
try {
await target.transform(<GetAgeDto>{ dob: 'null' }, metadata);
expect(true).toBe(false);
} catch (err) {
expect(err.getResponse().message).toEqual('Invalid dob timestamp');
}
});

NestJS - Add additional metadata to Pipes

Is there a way to add additional metadata to a NestJS pipe?
The metadata property has these values:
export interface ArgumentMetadata {
type: 'body' | 'query' | 'param' | 'custom';
metatype?: Type<any>;
data?: string;
}
See: https://docs.nestjs.com/pipes
I was able to add additional metadata via a custom parameter decorator, and a custom pipe.
import { createParamDecorator} from '#nestjs/common'
export const ExtractIdFromBody = createParamDecorator(
(
{
property,
entityLookupProperty = 'id'
}: {
property: string
entityLookupProperty?: string
},
req
) => {
const value = get(req.body, property)
return {
value,
entityLookupProperty // the extra property
}
}
)
Then I used a the decorator like this:
#Post()
#UsePipes(new ValidationPipe({ transform: true }))
async doThing(
#ExtractIdFromBody({ property: 'userId', entityLookupProperty: 'someProperty' }, GetEntityOr404Pipe) entity: Entity,
): Promise<Entity[]> {
return await this.Service.doThing(entity)
}

Resources