importhttpfrom'http';import{createHandler}from'graphql-sse';// Create the GraphQL over SSE handlerconsthandler=createHandler({
schema,// from the previous step});// Create a HTTP server using the handler on `/graphql/stream`constserver=http.createServer((req,res)=>{if(req.url.startsWith('/graphql/stream'))returnhandler(req,res);returnres.writeHead(404).end();});server.listen(4000);console.log('Listening to port 4000');
importfsfrom'fs';importhttp2from'http2';import{createHandler}from'graphql-sse';// Create the GraphQL over SSE handlerconsthandler=createHandler({
schema,// from the previous step});// Create a HTTP/2 server using the handler on `/graphql/stream`constserver=http2.createSecureServer({key: fs.readFileSync('localhost-privkey.pem'),cert: fs.readFileSync('localhost-cert.pem'),},(req,res)=>{if(req.url.startsWith('/graphql/stream'))returnhandler(req,res);returnres.writeHead(404).end();},);server.listen(4000);console.log('Listening to port 4000');
importexpressfrom'express';// yarn add expressimport{createHandler}from'graphql-sse';// Create the GraphQL over SSE handlerconsthandler=createHandler({ schema });// Create an express app serving all methods on `/graphql/stream`constapp=express();app.use('/graphql/stream',handler);app.listen(4000);console.log('Listening to port 4000');
importFastifyfrom'fastify';// yarn add fastifyimport{createHandler}from'graphql-sse';// Create the GraphQL over SSE handlerconsthandler=createHandler({ schema });// Create a fastify instance serving all methods on `/graphql/stream`constfastify=Fastify();fastify.all('/graphql/stream',(req,res)=>handler(req.raw,res.raw,req.body,// fastify reads the body for you),);fastify.listen(4000);console.log('Listening to port 4000');
Use the client
import{createClient}from'graphql-sse';constclient=createClient({// singleConnection: true, preferred for HTTP/1 enabled servers. read more belowurl: 'http://localhost:4000/graphql/stream',});// query(async()=>{constresult=awaitnewPromise((resolve,reject)=>{letresult;client.subscribe({query: '{ hello }',},{next: (data)=>(result=data),error: reject,complete: ()=>resolve(result),},);});expect(result).toEqual({hello: 'world'});})();// subscription(async()=>{constonNext=()=>{/* handle incoming values */};letunsubscribe=()=>{/* complete the subscription */};awaitnewPromise((resolve,reject)=>{unsubscribe=client.subscribe({query: 'subscription { greetings }',},{next: onNext,error: reject,complete: resolve,},);});expect(onNext).toBeCalledTimes(5);// we say "Hi" in 5 languages})();
请发表评论