Skip to content

Commit

Permalink
refactor: drop brackets from single statement if conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Mar 25, 2021
1 parent 98b590f commit 84462c8
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 123 deletions.
30 changes: 9 additions & 21 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,7 @@ export function createClient(options: ClientOptions): Client {
// @ts-expect-error: Support more browsers
window.MozWebSocket;
}
if (!ws) {
throw new Error('WebSocket implementation missing');
}
if (!ws) throw new Error('WebSocket implementation missing');
const WebSocketImpl = ws;

// websocket status emitter, subscriptions are handled differently
Expand Down Expand Up @@ -386,11 +384,10 @@ export function createClient(options: ClientOptions): Client {
emitter.emit('message', message);
if (acknowledged) return; // already connected and acknowledged

if (message.type !== MessageType.ConnectionAck) {
if (message.type !== MessageType.ConnectionAck)
throw new Error(
`First message cannot be of type ${message.type}`,
);
}
acknowledged = true;
emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged
retries = 0; // reset the retries on connect
Expand Down Expand Up @@ -459,27 +456,21 @@ export function createClient(options: ClientOptions): Client {
4409, // Subscriber for <id> already exists (distinction is very important)
4429, // Too many initialisation requests
].includes(errOrCloseEvent.code)
) {
)
throw errOrCloseEvent;
}

// disposed or normal closure (completed), shouldnt try again
if (
disposed ||
(isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000)
) {
)
return false;
}

// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts) {
throw errOrCloseEvent;
}
if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent;

// throw fatal connection problems immediately
if (isFatalConnectionProblem(errOrCloseEvent)) {
throw errOrCloseEvent;
}
if (isFatalConnectionProblem(errOrCloseEvent)) throw errOrCloseEvent;

// looks good, start retrying
return (retrying = true);
Expand Down Expand Up @@ -533,10 +524,8 @@ export function createClient(options: ClientOptions): Client {
const unlisten = emitter.on('message', (message) => {
switch (message.type) {
case MessageType.Next: {
if (message.id === id) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sink.next(message.payload as any);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (message.id === id) sink.next(message.payload as any);
return;
}
case MessageType.Error: {
Expand Down Expand Up @@ -568,15 +557,14 @@ export function createClient(options: ClientOptions): Client {
);

releaserRef.current = () => {
if (!completed && socket.readyState === WebSocketImpl.OPEN) {
if (!completed && socket.readyState === WebSocketImpl.OPEN)
// if not completed already and socket is open, send complete message to server on release
socket.send(
stringifyMessage<MessageType.Complete>({
id: id,
type: MessageType.Complete,
}),
);
}
release();
};

Expand Down
65 changes: 23 additions & 42 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,8 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
const connectionInitWait =
connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout)
? setTimeout(() => {
if (!ctx.connectionInitReceived) {
if (!ctx.connectionInitReceived)
socket.close(4408, 'Connection initialisation timeout');
}
}, connectionInitWaitTimeout)
: null;

Expand All @@ -483,21 +482,19 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
}
switch (message.type) {
case MessageType.ConnectionInit: {
if (ctx.connectionInitReceived) {
if (ctx.connectionInitReceived)
return socket.close(4429, 'Too many initialisation requests');
}

// @ts-expect-error: I can write
ctx.connectionInitReceived = true;

if (isObject(message.payload)) {
if (isObject(message.payload))
// @ts-expect-error: I can write
ctx.connectionParams = message.payload;
}

const permittedOrPayload = await onConnect?.(ctx);
if (permittedOrPayload === false) {
if (permittedOrPayload === false)
return socket.close(4403, 'Forbidden');
}

await socket.send(
stringifyMessage<MessageType.ConnectionAck>(
Expand All @@ -518,14 +515,11 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
return;
}
case MessageType.Subscribe: {
if (!ctx.acknowledged) {
return socket.close(4401, 'Unauthorized');
}
if (!ctx.acknowledged) return socket.close(4401, 'Unauthorized');

const { id } = message;
if (id in ctx.subscriptions) {
if (id in ctx.subscriptions)
return socket.close(4409, `Subscriber for ${id} already exists`);
}

// if this turns out to be a streaming operation, the subscription value
// will change to an `AsyncIterable`, otherwise it will stay as is
Expand All @@ -544,12 +538,11 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
args,
result,
);
if (maybeResult) {
if (maybeResult)
nextMessage = {
...nextMessage,
payload: maybeResult,
};
}
await socket.send(
stringifyMessage<MessageType.Next>(nextMessage),
);
Expand All @@ -561,12 +554,11 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
payload: errors,
};
const maybeErrors = await onError?.(ctx, errorMessage, errors);
if (maybeErrors) {
if (maybeErrors)
errorMessage = {
...errorMessage,
payload: maybeErrors,
};
}
await socket.send(
stringifyMessage<MessageType.Error>(errorMessage),
);
Expand All @@ -577,32 +569,29 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
type: MessageType.Complete,
};
await onComplete?.(ctx, completeMessage);
if (notifyClient) {
if (notifyClient)
await socket.send(
stringifyMessage<MessageType.Complete>(completeMessage),
);
}
},
};

let execArgs: ExecutionArgs;
const maybeExecArgsOrErrors = await onSubscribe?.(ctx, message);
if (maybeExecArgsOrErrors) {
if (areGraphQLErrors(maybeExecArgsOrErrors)) {
if (areGraphQLErrors(maybeExecArgsOrErrors))
return await emit.error(maybeExecArgsOrErrors);
} else if (Array.isArray(maybeExecArgsOrErrors)) {
else if (Array.isArray(maybeExecArgsOrErrors))
throw new Error(
'Invalid return value from onSubscribe hook, expected an array of GraphQLError objects',
);
}
// not errors, is exec args
execArgs = maybeExecArgsOrErrors;
} else {
if (!schema) {
// you either provide a schema dynamically through
// `onSubscribe` or you set one up during the server setup
// you either provide a schema dynamically through
// `onSubscribe` or you set one up during the server setup
if (!schema)
throw new Error('The GraphQL schema is not provided');
}

const { operationName, query, variables } = message.payload;
execArgs = {
Expand All @@ -615,53 +604,45 @@ export function makeServer<E = unknown>(options: ServerOptions<E>): Server<E> {
execArgs.schema,
execArgs.document,
);
if (validationErrors.length > 0) {
if (validationErrors.length > 0)
return await emit.error(validationErrors);
}
}

const operationAST = getOperationAST(
execArgs.document,
execArgs.operationName,
);
if (!operationAST) {
if (!operationAST)
return await emit.error([
new GraphQLError('Unable to identify operation'),
]);
}

// if `onSubscribe` didnt specify a rootValue, inject one
if (!('rootValue' in execArgs)) {
if (!('rootValue' in execArgs))
execArgs.rootValue = roots?.[operationAST.operation];
}

// if `onSubscribe` didn't specify a context, inject one
if (!('contextValue' in execArgs)) {
if (!('contextValue' in execArgs))
execArgs.contextValue =
typeof context === 'function'
? await context(ctx, message, execArgs)
: context;
}

// the execution arguments have been prepared
// perform the operation and act accordingly
let operationResult;
if (operationAST.operation === 'subscription') {
if (operationAST.operation === 'subscription')
operationResult = await subscribe(execArgs);
} else {
// operation === 'query' || 'mutation'
operationResult = await execute(execArgs);
}
// operation === 'query' || 'mutation'
else operationResult = await execute(execArgs);

const maybeResult = await onOperation?.(
ctx,
message,
execArgs,
operationResult,
);
if (maybeResult) {
operationResult = maybeResult;
}
if (maybeResult) operationResult = maybeResult;

if (isAsyncIterable(operationResult)) {
/** multiple emitted results */
Expand Down
21 changes: 6 additions & 15 deletions src/tests/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,13 @@ function tsubscribe<T = unknown>(
test?.(result);
resolve();
}
if (results.length > 0) {
return done();
}
if (results.length > 0) return done();
emitter.once('next', done);
if (expire) {
if (expire)
setTimeout(() => {
emitter.off('next', done); // expired
resolve();
}, expire);
}
});
},
waitForError: (test, expire) => {
Expand All @@ -83,16 +80,13 @@ function tsubscribe<T = unknown>(
test?.(error);
resolve();
}
if (error) {
return done();
}
if (error) return done();
emitter.once('err', done);
if (expire) {
if (expire)
setTimeout(() => {
emitter.off('err', done); // expired
resolve();
}, expire);
}
});
},
waitForComplete: (test, expire) => {
Expand All @@ -102,16 +96,13 @@ function tsubscribe<T = unknown>(
test?.();
resolve();
}
if (completed) {
return done();
}
if (completed) return done();
emitter.once('complete', done);
if (expire) {
if (expire)
setTimeout(() => {
emitter.off('complete', done); // expired
resolve();
}, expire);
}
});
},
dispose,
Expand Down
Loading

0 comments on commit 84462c8

Please sign in to comment.