Nom du fichier : Sans nom
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import typeDefs from "./typeDefs/index.js";
import resolvers from "./resolvers/index.js";
import { makeExecutableSchema } from '@graphql-tools/schema';
import { upperDirectiveTransformer } from './directives/upperDirective.js';
import { createAuthorLoader } from './dataloaders/authorLoader.js';
import { createCategoryLoader } from './dataloaders/categoryLoader.js';
import express from "express"
import http from "node:http"
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { expressMiddleware } from "@as-integrations/express5";
import cors from "cors"
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/use/ws"
const corsOptions = {
origin: ["http://localhost:5173"]
}
const authors = [
{
id: 'A1',
lastname: 'Kubrick',
firstname: 'Stanley',
age: 74
},
{
id: 'A2',
lastname: 'K. Dick',
firstname: 'Philip',
age: 89
},
{
id: 'A3',
lastname: 'Damasio',
firstname: 'Alain',
age: 63
},
];
// Data
export const categories = [
{
id: 'SF',
description: 'Science-Fiction'
},
{
id: 'POL',
description: 'Polar'
},
{
id: 'DR',
description: 'Drama'
},
{
id: 'B',
description: 'Biography'
},
];
async function startApolloServer() {
const app = express();
const httpServer = http.createServer(app);
const wsServer = new WebSocketServer({
server: httpServer,
path: "/graphql"
});
let schema = makeExecutableSchema( { typeDefs, resolvers }) ;
schema = upperDirectiveTransformer(schema, "upper");
const serverCleanup = useServer({schema}, wsServer)
const server = new ApolloServer({
schema,
plugins: [ApolloServerPluginDrainHttpServer({httpServer}), {
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
}
}
}
}],
});
await server.start();
app.use('/graphql', cors(corsOptions), express.json(), expressMiddleware(server, {
context: ({req, res}) => {
console.log(req.headers);
return { loaders: { author: createAuthorLoader(authors), category: createCategoryLoader(categories) } }
}
}));
await new Promise((resolve) => httpServer.listen({port:4000}, resolve));
console.log('Server ready at http://localhost:4000/graphql');
}
startApolloServer()