Skip to content

Commit

Permalink
feat: Centralise expected close codes in CloseCode enum
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Aug 21, 2021
1 parent dedcc6e commit d10a75c
Show file tree
Hide file tree
Showing 13 changed files with 193 additions and 56 deletions.
23 changes: 14 additions & 9 deletions README.md
Expand Up @@ -745,7 +745,7 @@ const client = createClient({
// minimal version of `import { useServer } from 'graphql-ws/lib/use/ws';`

import ws from 'ws'; // yarn add ws
import { makeServer } from 'graphql-ws';
import { makeServer, CloseCode } from 'graphql-ws';
import { schema } from './my-graphql-schema';

// make
Expand Down Expand Up @@ -779,7 +779,7 @@ wsServer.on('connection', (socket, request) => {
} catch (err) {
// all errors that could be thrown during the
// execution of operations will be caught here
socket.close(4500, err.message);
socket.close(CloseCode.InternalServerError, err.message);
}
}),
},
Expand All @@ -802,7 +802,7 @@ wsServer.on('connection', (socket, request) => {

import http from 'http';
import ws from 'ws'; // yarn add ws
import { makeServer } from 'graphql-ws';
import { makeServer, CloseCode } from 'graphql-ws';
import { schema } from './my-graphql-schema';
import { validate } from './my-auth';

Expand Down Expand Up @@ -875,7 +875,7 @@ wsServer.on('connection', (socket, request) => {
if (err instanceof Forbidden) {
// your magic
} else {
socket.close(4500, err.message);
socket.close(CloseCode.InternalServerError, err.message);
}
}
});
Expand All @@ -897,7 +897,12 @@ wsServer.on('connection', (socket, request) => {

```ts
import ws from 'ws'; // yarn add ws
import { makeServer, stringifyMessage, MessageType } from 'graphql-ws';
import {
makeServer,
CloseCode,
stringifyMessage,
MessageType,
} from 'graphql-ws';
import { schema } from './my-graphql-schema';

// make
Expand Down Expand Up @@ -946,7 +951,7 @@ wsServer.on('connection', (socket, request) => {
} catch (err) {
// all errors that could be thrown during the
// execution of operations will be caught here
socket.close(4500, err.message);
socket.close(CloseCode.InternalServerError, err.message);
}
}),
// pong received, clear termination timeout
Expand Down Expand Up @@ -1496,7 +1501,7 @@ useServer(
```typescript
// 📺 client

import { createClient } from 'graphql-ws';
import { createClient, CloseCode } from 'graphql-ws';
import {
getCurrentToken,
getCurrentTokenExpiresIn,
Expand Down Expand Up @@ -1540,14 +1545,14 @@ const client = createClient({
// will set the token refresh flag to true
tokenExpiryTimeout = setTimeout(() => {
if (socket.readyState === WebSocket.OPEN)
socket.close(4403, 'Unauthorized');
socket.close(CloseCode.Unauthorized, 'Unauthorized');
}, getCurrentTokenExpiresIn());
},
closed: (event) => {
// if closed with the `4403: Forbidden` close event
// the client or the server is communicating that the token
// is no longer valid and should be therefore refreshed
if (event.code === 4403) shouldRefreshToken = true;
if (event.code === CloseCode.Forbidden) shouldRefreshToken = true;
},
},
});
Expand Down
72 changes: 72 additions & 0 deletions docs/enums/common.CloseCode.md
@@ -0,0 +1,72 @@
[graphql-ws](../README.md) / [common](../modules/common.md) / CloseCode

# Enumeration: CloseCode

[common](../modules/common.md).CloseCode

`graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](/PROTOCOL.md).

## Table of contents

### Enumeration members

- [BadRequest](common.CloseCode.md#badrequest)
- [ConnectionInitialisationTimeout](common.CloseCode.md#connectioninitialisationtimeout)
- [Forbidden](common.CloseCode.md#forbidden)
- [InternalServerError](common.CloseCode.md#internalservererror)
- [SubprotocolNotAcceptable](common.CloseCode.md#subprotocolnotacceptable)
- [SubscriberAlreadyExists](common.CloseCode.md#subscriberalreadyexists)
- [TooManyInitialisationRequests](common.CloseCode.md#toomanyinitialisationrequests)
- [Unauthorized](common.CloseCode.md#unauthorized)

## Enumeration members

### BadRequest

**BadRequest** = `4400`

___

### ConnectionInitialisationTimeout

**ConnectionInitialisationTimeout** = `4408`

___

### Forbidden

**Forbidden** = `4403`

___

### InternalServerError

**InternalServerError** = `4500`

___

### SubprotocolNotAcceptable

**SubprotocolNotAcceptable** = `4406`

___

### SubscriberAlreadyExists

**SubscriberAlreadyExists** = `4409`

Subscriber distinction is very important

___

### TooManyInitialisationRequests

**TooManyInitialisationRequests** = `4429`

___

### Unauthorized

**Unauthorized** = `4401`

Tried subscribing before connect ack
7 changes: 7 additions & 0 deletions docs/modules/client.md
Expand Up @@ -6,6 +6,7 @@

### References

- [CloseCode](client.md#closecode)
- [CompleteMessage](client.md#completemessage)
- [ConnectionAckMessage](client.md#connectionackmessage)
- [ConnectionInitMessage](client.md#connectioninitmessage)
Expand Down Expand Up @@ -347,6 +348,12 @@ Creates a disposable GraphQL over WebSocket client.

## Other

### CloseCode

Re-exports: [CloseCode](../enums/common.CloseCode.md)

___

### CompleteMessage

Re-exports: [CompleteMessage](../interfaces/common.CompleteMessage.md)
Expand Down
1 change: 1 addition & 0 deletions docs/modules/common.md
Expand Up @@ -6,6 +6,7 @@

### Enumerations

- [CloseCode](../enums/common.CloseCode.md)
- [MessageType](../enums/common.MessageType.md)

### Interfaces
Expand Down
19 changes: 10 additions & 9 deletions src/__tests__/client.ts
Expand Up @@ -6,6 +6,7 @@ import WebSocket from 'ws';
import { EventEmitter } from 'events';
import { createClient, Client, EventListener } from '../client';
import {
CloseCode,
MessageType,
parseMessage,
stringifyMessage,
Expand Down Expand Up @@ -212,7 +213,7 @@ it('should close with error message during connecting issues', async () => {

await sub.waitForError((err) => {
const event = err as CloseEvent;
expect(event.code).toBe(4400);
expect(event.code).toBe(CloseCode.BadRequest);
expect(event.reason).toBe('Welcome');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -272,7 +273,7 @@ it('should close the socket if the `connectionParams` rejects or throws', async
let sub = tsubscribe(client, { query: '{ getValue }' });
await sub.waitForError((err) => {
const event = err as CloseEvent;
expect(event.code).toBe(4400);
expect(event.code).toBe(CloseCode.BadRequest);
expect(event.reason).toBe('No auth?');
expect(event.wasClean).toBeTruthy();
});
Expand All @@ -287,7 +288,7 @@ it('should close the socket if the `connectionParams` rejects or throws', async
sub = tsubscribe(client, { query: '{ getValue }' });
await sub.waitForError((err) => {
const event = err as CloseEvent;
expect(event.code).toBe(4400);
expect(event.code).toBe(CloseCode.BadRequest);
expect(event.reason).toBe('No auth?');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -1209,13 +1210,13 @@ describe('reconnecting', () => {
console.warn = () => {
/* hide warnings for test */
};
await testCloseCode(4406);
await testCloseCode(CloseCode.SubprotocolNotAcceptable);
console.warn = warn;
await testCloseCode(4500);
await testCloseCode(4400);
await testCloseCode(4401);
await testCloseCode(4409);
await testCloseCode(4429);
await testCloseCode(CloseCode.InternalServerError);
await testCloseCode(CloseCode.BadRequest);
await testCloseCode(CloseCode.Unauthorized);
await testCloseCode(CloseCode.SubscriberAlreadyExists);
await testCloseCode(CloseCode.TooManyInitialisationRequests);
});

it('should report fatal connection problems immediately', async () => {
Expand Down
15 changes: 8 additions & 7 deletions src/__tests__/server.ts
Expand Up @@ -11,6 +11,7 @@ import {
import { makeServer } from '../server';
import {
GRAPHQL_TRANSPORT_WS_PROTOCOL,
CloseCode,
MessageType,
parseMessage,
stringifyMessage,
Expand Down Expand Up @@ -439,7 +440,7 @@ describe('Connect', () => {
);

await client.waitForClose((event) => {
expect(event.code).toBe(4403);
expect(event.code).toBe(CloseCode.Forbidden);
expect(event.reason).toBe('Forbidden');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -536,7 +537,7 @@ describe('Connect', () => {
await (
await createTClient(url)
).waitForClose((event) => {
expect(event.code).toBe(4408);
expect(event.code).toBe(CloseCode.ConnectionInitialisationTimeout);
expect(event.reason).toBe('Connection initialisation timeout');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -590,7 +591,7 @@ describe('Connect', () => {
}, 10);

await client.waitForClose((event) => {
expect(event.code).toBe(4429);
expect(event.code).toBe(CloseCode.TooManyInitialisationRequests);
expect(event.reason).toBe('Too many initialisation requests');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -618,7 +619,7 @@ describe('Connect', () => {
);

await client.waitForClose((event) => {
expect(event.code).toBe(4429);
expect(event.code).toBe(CloseCode.TooManyInitialisationRequests);
expect(event.reason).toBe('Too many initialisation requests');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -756,7 +757,7 @@ describe('Subscribe', () => {
);

await client.waitForClose((event) => {
expect(event.code).toBe(4401);
expect(event.code).toBe(CloseCode.Unauthorized);
expect(event.reason).toBe('Unauthorized');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -1401,7 +1402,7 @@ describe('Subscribe', () => {
);

await client.waitForClose((event) => {
expect(event.code).toBe(4409);
expect(event.code).toBe(CloseCode.SubscriberAlreadyExists);
expect(event.reason).toBe('Subscriber for not-unique already exists');
expect(event.wasClean).toBeTruthy();
});
Expand Down Expand Up @@ -1446,7 +1447,7 @@ describe('Subscribe', () => {
);

await client.waitForClose((event) => {
expect(event.code).toBe(4409);
expect(event.code).toBe(CloseCode.SubscriberAlreadyExists);
expect(event.reason).toBe('Subscriber for not-unique already exists');
expect(event.wasClean).toBeTruthy();
});
Expand Down

0 comments on commit d10a75c

Please sign in to comment.