42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
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) {
|
|
// Only handle POST requests
|
|
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) {
|
|
return res.status(400).json({
|
|
errors: [
|
|
{
|
|
message:
|
|
'Must provide a valid GraphQL query, mutation, or subscription.',
|
|
},
|
|
],
|
|
});
|
|
}
|
|
// handle query only contain \n
|
|
if (query.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();
|
|
}
|
|
}
|