feat(example): minimal GraphQL with query/mutation and an SSE subscription over rooms
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
5 files changed
+125
No files matched your search
@@ -269,6 +269,40 @@ const app = createApp({
|
||||
|
||||
Overrides replace only the named token's runner; the rest of the graph is untouched.
|
||||
|
||||
## Runnable examples
|
||||
|
||||
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
||||
|
||||
### CRUD — methods, query, JSON & urlencoded body
|
||||
|
||||
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
||||
read the payload via `@body()` — the same handler accepts both `application/json` and
|
||||
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
||||
rows throw `NotFound` (→ 404).
|
||||
|
||||
See [`example/crud.ts`](../example/crud.ts).
|
||||
|
||||
### Chat — rooms + handshake auth
|
||||
|
||||
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
||||
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
|
||||
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
|
||||
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
|
||||
primitive (one instance app-wide).
|
||||
|
||||
See [`example/chat.ts`](../example/chat.ts).
|
||||
|
||||
### GraphQL — query/mutation over POST, subscription over SSE
|
||||
|
||||
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
||||
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
||||
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
||||
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
||||
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
||||
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
||||
|
||||
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
||||
|
||||
## The one rule to remember
|
||||
|
||||
```
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, graphql, subscribe, parse } from 'graphql';
|
||||
import { createApp, Route, Post, Sse, Module, body, needs, isAsyncIterable, Rooms } from '../src/index';
|
||||
|
||||
interface Message { text: string }
|
||||
const store: Message[] = [];
|
||||
const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } });
|
||||
|
||||
function buildSchema(rooms: Rooms): GraphQLSchema {
|
||||
return new GraphQLSchema({
|
||||
query: new GraphQLObjectType({ name: 'Query', fields: {
|
||||
messages: { type: new GraphQLList(MessageType), resolve: () => store },
|
||||
} }),
|
||||
mutation: new GraphQLObjectType({ name: 'Mutation', fields: {
|
||||
postMessage: { type: MessageType, args: { text: { type: new GraphQLNonNull(GraphQLString) } },
|
||||
resolve: (_root, { text }: { text: string }) => { const m = { text }; store.push(m); rooms.room('messages').push(m); return m; } },
|
||||
} }),
|
||||
subscription: new GraphQLObjectType({ name: 'Subscription', fields: {
|
||||
messageAdded: { type: MessageType,
|
||||
subscribe: () => rooms.room<Message>('messages'), // Channel is the AsyncIterable source
|
||||
resolve: (payload: Message) => payload },
|
||||
} }),
|
||||
});
|
||||
}
|
||||
|
||||
@Route('/graphql')
|
||||
class GraphQLController {
|
||||
@Post('')
|
||||
async run(@body() input: any, @needs('rooms') rooms: Rooms) {
|
||||
return graphql({ schema: buildSchema(rooms), source: input?.query ?? '', variableValues: input?.variables });
|
||||
}
|
||||
|
||||
@Sse('/stream')
|
||||
async stream(@needs('rooms') rooms: Rooms) {
|
||||
const result = await subscribe({ schema: buildSchema(rooms), document: parse('subscription { messageAdded { text } }') });
|
||||
if (!isAsyncIterable(result)) throw new Error('subscription failed'); // subscribe() returns a single ExecutionResult on error
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [GraphQLController] })
|
||||
class GraphQLModule {}
|
||||
|
||||
export const app = createApp({ modules: [GraphQLModule] });
|
||||
|
||||
if (require.main === module) {
|
||||
app.listen(4200).then(() => console.log('graphql on http://localhost:4200/graphql'));
|
||||
}
|
||||
Generated
+19
@@ -14,9 +14,18 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"graphql": "^16.9.0",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ws": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -1063,6 +1072,16 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/graphql": {
|
||||
"version": "16.14.2",
|
||||
"resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz",
|
||||
"integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/loupe": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"graphql": "^16.9.0",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect, afterAll } from 'vitest';
|
||||
import { app } from '../../example/graphql';
|
||||
|
||||
let server: any; let base: string;
|
||||
afterAll(() => server?.close());
|
||||
const gql = (query: string, variables?: any) =>
|
||||
fetch(`${base}/graphql`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query, variables }) }).then((r) => r.json() as Promise<any>);
|
||||
|
||||
describe('graphql example', () => {
|
||||
it('runs a query and a mutation, and streams a subscription over SSE', async () => {
|
||||
server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
|
||||
|
||||
expect(await gql('{ messages { text } }')).toMatchObject({ data: { messages: expect.any(Array) } });
|
||||
|
||||
const res = await fetch(`${base}/graphql/stream`, { headers: { accept: 'text/event-stream' } });
|
||||
const reader = res.body!.getReader();
|
||||
await new Promise((r) => setTimeout(r, 50)); // let the subscription subscribe to the room before publishing
|
||||
await gql('mutation($t:String!){ postMessage(text:$t){ text } }', { t: 'hello-sub' });
|
||||
const dec = new TextDecoder(); let buf = '';
|
||||
while (!buf.includes('hello-sub')) buf += dec.decode((await reader.read()).value);
|
||||
expect(buf).toContain('hello-sub');
|
||||
await reader.cancel();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user