Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to TS #159

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/RRNLError.js → src/RRNLError.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/* @flow */

export default class RRNLError extends Error {
constructor(msg: string) {
super(msg);
this.name = 'RRNLError';
}
}

}
106 changes: 0 additions & 106 deletions src/RelayNetworkLayer.js

This file was deleted.

80 changes: 80 additions & 0 deletions src/RelayNetworkLayer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Network } from "relay-runtime";
import RelayRequest from "./RelayRequest";
import fetchWithMiddleware from "./fetchWithMiddleware";
import type { Middleware, MiddlewareSync, MiddlewareRaw, FetchFunction, FetchHookFunction, SubscribeFunction, RNLExecuteFunction } from "./definition";
export type RelayNetworkLayerOpts = {
subscribeFn?: SubscribeFunction;
beforeFetch?: FetchHookFunction;
noThrow?: boolean;
};
export default class RelayNetworkLayer {
_middlewares: Middleware[];
_rawMiddlewares: MiddlewareRaw[];
_middlewaresSync: RNLExecuteFunction[];
execute: RNLExecuteFunction;
executeWithEvents: any;
readonly fetchFn: FetchFunction;
readonly subscribeFn: SubscribeFunction | null | undefined;
readonly noThrow: boolean;

constructor(middlewares: Array<(Middleware | null | undefined) | MiddlewareSync | MiddlewareRaw>, opts?: RelayNetworkLayerOpts) {
this._middlewares = [];
this._rawMiddlewares = [];
this._middlewaresSync = [];
this.noThrow = false;
const mws = Array.isArray(middlewares) ? (middlewares as any) : [middlewares];
mws.forEach(mw => {
if (mw) {
if (mw.execute) {
this._middlewaresSync.push(mw.execute);
} else if (mw.isRawMiddleware) {
this._rawMiddlewares.push(mw);
} else {
this._middlewares.push(mw);
}
}
});

if (opts) {
this.subscribeFn = opts.subscribeFn;
this.noThrow = opts.noThrow === true;

// TODO deprecate
if (opts.beforeFetch) {
this._middlewaresSync.push((opts.beforeFetch as any));
}
}

this.fetchFn = (operation, variables, cacheConfig, uploadables) => {
for (let i = 0; i < this._middlewaresSync.length; i++) {
const res = this._middlewaresSync[i](operation, variables, cacheConfig, uploadables);

if (res) return res;
}

return {
subscribe: sink => {
const req = new RelayRequest(operation, variables, cacheConfig, uploadables);
const res = fetchWithMiddleware(req, this._middlewares, this._rawMiddlewares, this.noThrow);
res.then(value => {
sink.next(value);
sink.complete();
}, error => {
if (error && error.name && error.name === 'AbortError') {
sink.complete();
} else sink.error(error);
}) // avoid unhandled promise rejection error
.catch(() => {});
return () => {
req.cancel();
};
}
};
};

const network = Network.create(this.fetchFn, this.subscribeFn);
this.execute = network.execute;
this.executeWithEvents = network.executeWithEvents;
}

}
59 changes: 27 additions & 32 deletions src/RelayRequest.js → src/RelayRequest.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,34 @@
/* @flow */
import { Class } from "utility-types";
import type { ConcreteBatch, Variables, CacheConfig, UploadableMap, FetchOpts } from "./definition";
import RRNLError from "./RRNLError";

import type { ConcreteBatch, Variables, CacheConfig, UploadableMap, FetchOpts } from './definition';
import RRNLError from './RRNLError';

function getFormDataInterface(): ?Class<FormData> {
return (typeof window !== 'undefined' && window.FormData) || (global && global.FormData);
function getFormDataInterface(): Class<FormData> | null | undefined {
return typeof window !== 'undefined' && window.FormData || global && global.FormData;
}

export default class RelayRequest {
static lastGenId: number;
id: string;
fetchOpts: FetchOpts;

operation: ConcreteBatch;
variables: Variables;
cacheConfig: CacheConfig;
uploadables: ?UploadableMap;
controller: ?window.AbortController;

constructor(
operation: ConcreteBatch,
variables: Variables,
cacheConfig: CacheConfig,
uploadables?: ?UploadableMap
) {
uploadables: UploadableMap | null | undefined;
controller: window.AbortController | null | undefined;

constructor(operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, uploadables?: UploadableMap | null | undefined) {
this.operation = operation;
this.variables = variables;
this.cacheConfig = cacheConfig;
this.uploadables = uploadables;

this.id = this.operation.id || this.operation.name || this._generateID();

const fetchOpts: FetchOpts = {
method: 'POST',
headers: {},
body: this.prepareBody(),
body: this.prepareBody()
};

this.controller =
typeof window !== 'undefined' && window.AbortController ? new window.AbortController() : null;
this.controller = typeof window !== 'undefined' && window.AbortController ? new window.AbortController() : null;
if (this.controller) fetchOpts.signal = this.controller.signal;

this.fetchOpts = fetchOpts;
}

Expand All @@ -49,9 +37,13 @@ export default class RelayRequest {
}

prepareBody(): string | FormData {
const { uploadables } = this;
const {
uploadables
} = this;

if (uploadables) {
const _FormData_ = getFormDataInterface();

if (!_FormData_) {
throw new RRNLError('Uploading files without `FormData` interface does not supported.');
}
Expand All @@ -60,20 +52,18 @@ export default class RelayRequest {
formData.append('id', this.getID());
formData.append('query', this.getQueryString());
formData.append('variables', JSON.stringify(this.getVariables()));

Object.keys(uploadables).forEach((key) => {
Object.keys(uploadables).forEach(key => {
if (Object.prototype.hasOwnProperty.call(uploadables, key)) {
formData.append(key, uploadables[key]);
}
});

return formData;
}

return JSON.stringify({
id: this.getID(),
query: this.getQueryString(),
variables: this.getVariables(),
variables: this.getVariables()
});
}

Expand All @@ -85,6 +75,7 @@ export default class RelayRequest {
if (!this.constructor.lastGenId) {
this.constructor.lastGenId = 0;
}

this.constructor.lastGenId += 1;
return this.constructor.lastGenId.toString();
}
Expand All @@ -103,6 +94,7 @@ export default class RelayRequest {

isFormData(): boolean {
const _FormData_ = getFormDataInterface();

return !!_FormData_ && this.fetchOpts.body instanceof _FormData_;
}

Expand All @@ -111,14 +103,17 @@ export default class RelayRequest {
this.controller.abort();
return true;
}

return false;
}

clone(): RelayRequest {
// $FlowFixMe
const newRequest = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
newRequest.fetchOpts = { ...this.fetchOpts };
newRequest.fetchOpts.headers = { ...this.fetchOpts.headers };
return (newRequest: any);
newRequest.fetchOpts = { ...this.fetchOpts
};
newRequest.fetchOpts.headers = { ...this.fetchOpts.headers
};
return (newRequest as any);
}

}
Loading
Loading