Skip to content

Commit

Permalink
Migrate to TS
Browse files Browse the repository at this point in the history
  • Loading branch information
dr3 committed Feb 4, 2024
1 parent 7f366ea commit b723ca3
Show file tree
Hide file tree
Showing 32 changed files with 1,030 additions and 1,247 deletions.
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;
}

}
60 changes: 28 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,18 @@ 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

0 comments on commit b723ca3

Please sign in to comment.