38 lines
1015 B
TypeScript
38 lines
1015 B
TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
import { Request, Response, NextFunction } from 'express';
|
|
|
|
@Injectable()
|
|
export class GraphQLValidationMiddleware implements NestMiddleware {
|
|
use(req: Request, res: Response, next: NextFunction) {
|
|
// handle post request
|
|
if (
|
|
req.method === 'POST' &&
|
|
req.headers['content-type'] === 'application/json'
|
|
) {
|
|
const { query, mutation, subscription } = req.body;
|
|
|
|
// If none of these are present, return a custom error response
|
|
if (
|
|
!query &&
|
|
!mutation &&
|
|
!subscription &&
|
|
query.trim() === '' &&
|
|
mutation.trim() === '' &&
|
|
subscription.trim() === ''
|
|
) {
|
|
return res.status(400).json({
|
|
errors: [
|
|
{
|
|
message:
|
|
'Must provide a valid GraphQL query, mutation, or subscription.',
|
|
},
|
|
],
|
|
});
|
|
}
|
|
}
|
|
|
|
// Continue to the next middleware or GraphQL handler
|
|
next();
|
|
}
|
|
}
|