Skip to content

Commit

Permalink
feat: Simplify subscription payload needed
Browse files Browse the repository at this point in the history
  • Loading branch information
ilijaNL committed Mar 20, 2023
1 parent 47aa14d commit d585867
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 178 deletions.
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ useServer(
return {
start: async function (emit) {
for await (const l of iter) {
await emit({
id: message.id,
payload: { data: { greetings: l } },
type: MessageType.Next,
});
await emit({ data: { greetings: l } });
}
},
stop: () => {
Expand Down
16 changes: 0 additions & 16 deletions src/__tests__/__snapshots__/common.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,6 @@ exports[`should report invalid message {"id":"id","type":"subscribe","payload":"

exports[`should report invalid message {"id":"id","type":"subscribe","payload":[]} with descriptive error 1`] = `""subscribe" message expects the 'payload' property to be an object, but got array"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"operationName":{},"query":""}} with descriptive error 1`] = `""subscribe" message payload expects the 'operationName' property to be a string or nullish or missing, but got object"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"operationName":0,"query":""}} with descriptive error 1`] = `""subscribe" message payload expects the 'operationName' property to be a string or nullish or missing, but got number"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"query":"","extensions":""}} with descriptive error 1`] = `""subscribe" message payload expects the 'extensions' property to be a an object or nullish or missing, but got string"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"query":"","extensions":0}} with descriptive error 1`] = `""subscribe" message payload expects the 'extensions' property to be a an object or nullish or missing, but got number"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"query":"","variables":""}} with descriptive error 1`] = `""subscribe" message payload expects the 'variables' property to be a an object or nullish or missing, but got string"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"query":{}}} with descriptive error 1`] = `""subscribe" message payload expects the 'query' property to be a string, but got object"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{"query":0}} with descriptive error 1`] = `""subscribe" message payload expects the 'query' property to be a string, but got number"`;

exports[`should report invalid message {"id":"id","type":"subscribe","payload":{}} with descriptive error 1`] = `""subscribe" message payload expects the 'query' property to be a string, but got undefined"`;

exports[`should report invalid message {"id":"id","type":"subscribe"} with descriptive error 1`] = `""subscribe" message expects the 'payload' property to be an object, but got undefined"`;

exports[`should report invalid message {"id":0,"type":"complete"} with descriptive error 1`] = `""complete" message expects the 'id' property to be a string, but got number"`;
Expand Down
59 changes: 0 additions & 59 deletions src/__tests__/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,65 +71,6 @@ it.each([
type: MessageType.Subscribe,
payload: '',
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
query: 0,
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
query: {},
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
operationName: 0,
query: '',
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
operationName: {},
query: '',
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
query: '',
variables: '',
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
query: '',
extensions: '',
},
},
{
id: 'id',
type: MessageType.Subscribe,
payload: {
query: '',
extensions: 0,
},
},

// invalid next message
{
Expand Down
44 changes: 10 additions & 34 deletions src/__tests__/fixtures/simple.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
ErrorMessage,
MessageType,
NextMessage,
SubscribeMessage,
} from '../../common';
import { ErrorMessage, NextMessage } from '../../common';
import { ServerOptions } from '../../server';

// use for dispatching a `pong` to the `ping` subscription
Expand Down Expand Up @@ -33,14 +28,9 @@ export const LATE_SUB = 'subscription { lateReturn }';
export const GREETINGS = 'subscription { greetings }';

async function getValue(
message: SubscribeMessage,
emit: (message: NextMessage) => Promise<void>,
emit: (message: NextMessage['payload']) => Promise<void>,
) {
await emit({
id: message.id,
payload: { data: { getValue: 'value' } },
type: MessageType.Next,
});
await emit({ data: { getValue: 'value' } });
}

export const simpleSubscribe: ServerOptions['createSubscription'] = ({
Expand All @@ -49,7 +39,7 @@ export const simpleSubscribe: ServerOptions['createSubscription'] = ({
if (message.payload.query === GET_VALUE_QUERY) {
return {
start(emit) {
return getValue(message, emit);
return getValue(emit);
},
stop() {
//
Expand All @@ -67,11 +57,7 @@ export const simpleSubscribe: ServerOptions['createSubscription'] = ({
return {
start: async function (emit) {
for await (const l of iter) {
await emit({
id: message.id,
payload: { data: { greetings: l } },
type: MessageType.Next,
});
await emit({ data: { greetings: l } });
}
},
stop: () => {
Expand Down Expand Up @@ -111,11 +97,7 @@ export const simpleSubscribe: ServerOptions['createSubscription'] = ({
return {
start: async function (emit) {
for await (const l of iterator) {
await emit({
id: message.id,
payload: { data: { ping: l } },
type: MessageType.Next,
});
await emit({ data: { ping: l } });
}
},
stop: () => {
Expand Down Expand Up @@ -149,11 +131,7 @@ export const simpleSubscribe: ServerOptions['createSubscription'] = ({
return {
start: async function (emit) {
for await (const l of iterator) {
await emit({
id: message.id,
payload: { data: { ping: l } },
type: MessageType.Next,
});
await emit({ data: { ping: l } });
}
},
stop: () => {
Expand All @@ -167,10 +145,8 @@ export const simpleSubscribe: ServerOptions['createSubscription'] = ({
//
},
start: () =>
Promise.resolve<ErrorMessage>({
id: message.id,
payload: [{ message: 'unknown', name: 'operation not known' }],
type: MessageType.Error,
}),
Promise.resolve<ErrorMessage['payload']>([
{ message: 'unknown', name: 'operation not known' },
]),
};
};
24 changes: 8 additions & 16 deletions src/__tests__/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
parseMessage,
stringifyMessage,
ErrorMessage,
NextMessage,
ExecutionResult,
} from '../common';
import { GET_VALUE_QUERY, PING_SUB, simpleSubscribe } from './fixtures/simple';
import { createTClient, startWSTServer as startTServer } from './utils';
Expand Down Expand Up @@ -536,13 +536,9 @@ describe('Subscribe', () => {

const generator = gen();

async function run(emit: (msg: NextMessage) => Promise<void>) {
async function run(emit: (msg: ExecutionResult) => Promise<void>) {
for await (const res of generator) {
emit({
id: '1',
payload: { data: res },
type: MessageType.Next,
});
emit({ data: res });
}
}

Expand Down Expand Up @@ -610,14 +606,10 @@ describe('Subscribe', () => {
});

it('should execute the query and "error"', async () => {
const error: ErrorMessage = {
id: '1',
payload: [
{ name: 't', message: 'Report' },
{ name: 't', message: 'Me' },
],
type: MessageType.Error,
};
const error: ErrorMessage['payload'] = [
{ name: 't', message: 'Report' },
{ name: 't', message: 'Me' },
];
const { url } = await startTServer({
createSubscription() {
return {
Expand Down Expand Up @@ -653,7 +645,7 @@ describe('Subscribe', () => {
});

await client.waitForMessage(({ data }) => {
expect(parseMessage(data)).toEqual(error);
expect((parseMessage(data) as ErrorMessage).payload).toEqual(error);
});

await client.waitForClose(() => {
Expand Down
43 changes: 0 additions & 43 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,49 +240,6 @@ export function validateMessage(val: unknown): Message {
);
}

if (typeof val.payload.query !== 'string') {
throw new Error(
`"${
val.type
}" message payload expects the 'query' property to be a string, but got ${extendedTypeof(
val.payload.query,
)}`,
);
}

if (val.payload.variables != null && !isObject(val.payload.variables)) {
throw new Error(
`"${
val.type
}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.variables,
)}`,
);
}

if (
val.payload.operationName != null &&
extendedTypeof(val.payload.operationName) !== 'string'
) {
throw new Error(
`"${
val.type
}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${extendedTypeof(
val.payload.operationName,
)}`,
);
}

if (val.payload.extensions != null && !isObject(val.payload.extensions)) {
throw new Error(
`"${
val.type
}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.extensions,
)}`,
);
}

break;
}

Expand Down
15 changes: 10 additions & 5 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
PingMessage,
PongMessage,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
ExecutionResult,
} from './common';
import { isAsyncGenerator, isObject } from './utils';

Expand All @@ -29,8 +30,8 @@ export interface Subscription {
* Resolves when the subscription is done or with an ErrorMessage when subscription has an error when starting
*/
start(
emit: (message: NextMessage) => Promise<void>,
): Promise<ErrorMessage | void>;
emit: (message: ExecutionResult) => Promise<void>,
): Promise<ErrorMessage['payload'] | void>;
/**
* Stops this subscription
*/
Expand Down Expand Up @@ -535,12 +536,16 @@ class SubscriptionConnection<

this.subscriptions.set(id, sub);

const error = await sub.start((message: NextMessage) =>
this._send(id, message),
const error = await sub.start((result: ExecutionResult) =>
this._send(id, { id: id, payload: result, type: MessageType.Next }),
);
// resolved with error, just report and return
if (error) {
return await this._send(id, error);
return await this._send(id, {
id,
payload: error,
type: MessageType.Error,
});
}

await this._send(id, { type: MessageType.Complete, id: id });
Expand Down

0 comments on commit d585867

Please sign in to comment.