Skip to content

Instantly share code, notes, and snippets.

@hoangvvo
Last active March 10, 2021 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoangvvo/fa2901c5707eed116144426563fd6009 to your computer and use it in GitHub Desktop.
Save hoangvvo/fa2901c5707eed116144426563fd6009 to your computer and use it in GitHub Desktop.
import { GraphQLObjectType, GraphQLSchema, GraphQLString, parse, subscribe as gqlSubscribe } from "graphql";
function isAsyncIterable<T>(val: any): val is AsyncIterableIterator<T> {
return val != null && typeof val[Symbol.asyncIterator] === "function";
}
const NodeType = new GraphQLObjectType({
name: "Node",
fields: {
id: { type: GraphQLString }
}
})
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "Query",
fields: {
node: {
type: NodeType,
resolve() {
return { id: "" }
}
}
}
}),
subscription: new GraphQLObjectType({
name: "Subscription",
fields: {
nodes: {
type: NodeType,
// resolve(source) {
// return source;
// },
async *subscribe() {
for (let i = 0; i < 3; i++) {
yield {
id: i.toString()
};
}
},
}
}
})
});
async function subscribe(query: string) {
const document = parse(query);
return gqlSubscribe({ document, schema })
}
describe("subscription happy case", () => {
test("nodes and ids", async () => {
const sub = await subscribe(`
subscription {
nodes {
id
}
}
`);
if (isAsyncIterable(sub)) {
let i = 0;
for await (const val of sub) {
expect(val.data?.nodes?.id).toBe((i++).toString());
}
}
});
});
import { makeExecutableSchema } from "@graphql-tools/schema";
import { parse, subscribe as gqlSubscribe } from "graphql";
function isAsyncIterable<T>(val: any): val is AsyncIterableIterator<T> {
return val != null && typeof val[Symbol.asyncIterator] === "function";
}
const schema = makeExecutableSchema({
typeDefs: `
type Subscription {
nodes: Node
}
type Query {
node: String
}
type Node {
id: ID
}
`,
resolvers: {
Query: {
node: () => {
return {
id: ""
}
}
},
Subscription: {
nodes: {
async *subscribe() {
for (let i = 0; i < 3; i++) {
yield {
id: i.toString()
};
}
},
/**
* Without this resolver, the tests below would fail
*/
// resolve(source) {
// return source;
// }
}
}
}
});
async function subscribe(query: string) {
const document = parse(query);
return gqlSubscribe({ document, schema })
}
describe("subscription happy case", () => {
test("nodes and ids", async () => {
const sub = await subscribe(`
subscription {
nodes {
id
}
}
`);
if (isAsyncIterable(sub)) {
let i = 0;
for await (const val of sub) {
expect(val.data?.nodes?.id).toBe((i++).toString());
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment