Skip to content

Commit

Permalink
feat: add async mutation support (#217)
Browse files Browse the repository at this point in the history
Co-authored-by: Paul Brachmann <[email protected]>
Co-authored-by: Terris Linenbach <[email protected]>
  • Loading branch information
3 people authored Apr 15, 2021
1 parent de24bbc commit b7f34ac
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/mutation/relay-mutation.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { MetadataStorage } from '../common/metadata-storage.class';
import { InputArgFactory } from './input-arg';
import { PayloadTypeFactory } from './payload-type';
import { getClientMutationId } from './utils';
import { ensurePromise } from './utils/ensure-promise';

export type RelayMutationOptions = Omit<MutationOptions, 'nullable'>;

Expand All @@ -17,9 +18,9 @@ export function RelayMutation<T>(
* Resolver Interceptor
*/
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
descriptor.value = async function (...args: any[]) {
const clientMutationId = getClientMutationId(args);
const methodResult = originalMethod.apply(this, args);
const methodResult = await ensurePromise(originalMethod.apply(this, args));
return { ...methodResult, clientMutationId };
};

Expand Down
23 changes: 23 additions & 0 deletions src/mutation/utils/ensure-promise.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ensurePromise, isPromise } from './ensure-promise';

describe('isPromise', () => {
it('should return true for a Promise', () => {
expect(isPromise(Promise.resolve())).toBe(true);
});

it('should return false for everything else', () => {
expect(isPromise('not a Promise')).toBe(false);
expect(isPromise({ then: 'not a function' })).toBe(false);
});
});

describe('ensurePromise', () => {
it('should return the passed Promise', () => {
const promise = Promise.resolve();
expect(ensurePromise(promise)).toBe(promise);
});

it('should return everything else wrapped in a promise', () => {
expect(isPromise(ensurePromise('not a Promise'))).toBe(true);
});
});
6 changes: 6 additions & 0 deletions src/mutation/utils/ensure-promise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** Returns true if `maybePromise` is a Promise. */
export const isPromise = <T>(maybePromise: T | Promise<T>): maybePromise is Promise<T> =>
Boolean(typeof (maybePromise as any)?.then === 'function');

export const ensurePromise = <T>(maybePromise: T | Promise<T>) =>
isPromise(maybePromise) ? maybePromise : Promise.resolve(maybePromise);

0 comments on commit b7f34ac

Please sign in to comment.