1- import { ApolloServer } from '@apollo/server'
1+ import { ApolloServer , ApolloServerPlugin } from '@apollo/server'
22import { expressMiddleware } from '@apollo/server/express4'
33import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'
44import express from 'express'
@@ -8,6 +8,26 @@ import bodyParser from 'body-parser'
88import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache'
99
1010import { applyMiddleware } from 'graphql-middleware'
11+
12+ /**
13+ * Plugin to return HTTP 401 for FORBIDDEN errors (unauthorized mutations)
14+ */
15+ const httpStatusPlugin : ApolloServerPlugin = {
16+ async requestDidStart ( ) {
17+ return {
18+ async willSendResponse ( { response } ) {
19+ // Check if any error has FORBIDDEN code
20+ const hasForbiddenError = response . body . kind === 'single' &&
21+ response . body . singleResult . errors ?. some (
22+ ( err ) => err . extensions ?. code === 'FORBIDDEN'
23+ )
24+ if ( hasForbiddenError ) {
25+ response . http . status = 401
26+ }
27+ }
28+ }
29+ }
30+ }
1131import { graphqlSchema } from './graphql/resolvers.js'
1232import MutableAreaDataSource from './model/MutableAreaDataSource.js'
1333import ChangeLogDataSource from './model/ChangeLogDataSource.js'
@@ -47,7 +67,10 @@ export async function createServer (): Promise<{ app: express.Application, serve
4767 const server = new ApolloServer ( {
4868 introspection : true ,
4969 schema,
50- plugins : [ ApolloServerPluginDrainHttpServer ( { httpServer } ) ] ,
70+ plugins : [
71+ ApolloServerPluginDrainHttpServer ( { httpServer } ) ,
72+ httpStatusPlugin
73+ ] ,
5174 cache : new InMemoryLRUCache ( {
5275 max : 50 ,
5376 maxSize : 1024 * 1024 * 10
0 commit comments