Skip to content
This repository has been archived by the owner on Aug 20, 2020. It is now read-only.

run prettier on files #11

Merged
merged 6 commits into from
Jul 26, 2017
Merged
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
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,8 @@ jspm_packages
.yarn-integrity

#
dist
dist

# lockfiles
yarn.lock
package-lock.json
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ notifications:
email: false

before_install:
- npm install -g coveralls lerna
- lerna run -- prune
- npm install -g coveralls

install:
- lerna bootstrap

script:
- lerna run -- test
- npm test

after_success:
- npm run coverage
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

### vNEXT

### 0.4.0

- Move repository to lerna project [PR #10](https://github.com/apollographql/apollo-fetch/pull/10)
- Support batched requests [PR #10](https://github.com/apollographql/apollo-fetch/pull/10)

Expand Down
23 changes: 18 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,21 @@
"type": "git",
"url": "git+https://github.com/apollographql/apollo-fetch.git"
},
"scripts":{
"coverage" : "nyc --reporter=lcov lerna run -- coverage:test"
"scripts": {
"bootstrap": "npm i && lerna bootstrap",
"test": "lerna run -- test",
"lint-fix": "prettier --trailing-comma all --single-quote --write \"packages/*/{src,tests,benchmark}/**/*.{j,t}s*\"",
"lint-staged": "lint-staged",
"coverage": "nyc --reporter=lcov lerna run -- coverage:test"
},
"lint-staged": {
"*.ts*": [
"prettier --trailing-comma all --single-quote --write",
"git add"
],
"*.json*": ["prettier --write", "git add"]
},
"pre-commit": "lint-staged",
"devDependencies": {
"@types/chai": "^4.0.0",
"@types/chai-as-promised": "0.0.31",
Expand All @@ -19,19 +31,20 @@
"graphql": "^0.10.3",
"graphql-tag": "^2.4.2",
"lerna": "^2.0.0",
"lint-staged": "^4.0.2",
"lodash": "^4.17.4",
"mocha": "^3.2.0",
"nyc": "^11.0.3",
"pre-commit": "^1.2.2",
"prettier": "^1.5.3",
"rimraf": "^2.5.4",
"sinon": "^2.3.4",
"source-map-support": "^0.4.5",
"tslint": "^5.0.0",
"typescript": "^2.2.1"
},
"nyc": {
"exclude": [
"**/tests"
]
"exclude": ["**/tests"]
},
"//": {
"//": "lerna run <script name>",
Expand Down
6 changes: 2 additions & 4 deletions packages/apollo-fetch/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "apollo-fetch",
"version": "0.3.0",
"version": "0.4.0",
"description": "Lightweight implementation of fetch for GraphQL requests",
"author": "Evans Hauser <evanshauser@gmail.com>",
"contributors": [
Expand Down Expand Up @@ -58,8 +58,6 @@
"typescript": "^2.2.1"
},
"nyc": {
"exclude": [
"tests"
]
"exclude": ["tests"]
}
}
197 changes: 113 additions & 84 deletions packages/apollo-fetch/src/apollo-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import {
} from './types';
import 'isomorphic-fetch';

type WareStack = MiddlewareInterface[] | BatchMiddlewareInterface[] | AfterwareInterface[] | BatchAfterwareInterface[];
type WareStack =
| MiddlewareInterface[]
| BatchMiddlewareInterface[]
| AfterwareInterface[]
| BatchAfterwareInterface[];

function buildWareStack<M>(funcs: WareStack, modifiedObject: M, resolve) {
const next = () => {
Expand All @@ -32,12 +36,17 @@ function buildWareStack<M>(funcs: WareStack, modifiedObject: M, resolve) {
next();
}

export function constructDefaultOptions(requestOrRequests: GraphQLRequest | GraphQLRequest[], options: RequestInit): RequestInit {
export function constructDefaultOptions(
requestOrRequests: GraphQLRequest | GraphQLRequest[],
options: RequestInit,
): RequestInit {
let body;
try {
body = JSON.stringify(requestOrRequests);
} catch (e) {
throw new Error(`Network request failed. Payload is not serializable: ${e.message}`);
throw new Error(
`Network request failed. Payload is not serializable: ${e.message}`,
);
}

return {
Expand All @@ -47,15 +56,17 @@ export function constructDefaultOptions(requestOrRequests: GraphQLRequest | Grap
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
...(options.headers || []),
...options.headers || [],
},
};
}

function throwHttpError(response, error) {
let httpError;
if (response && response.status >= 300) {
httpError = new Error(`Network request failed with status ${response.status} - "${response.statusText}"`);
httpError = new Error(
`Network request failed with status ${response.status} - "${response.statusText}"`,
);
} else {
httpError = new Error(`Network request failed to return valid JSON`);
}
Expand All @@ -73,15 +84,14 @@ function throwBatchError(response) {
}

export function createApolloFetch(params: FetchOptions = {}): ApolloFetch {
const {constructOptions, customFetch} = params;
const { constructOptions, customFetch } = params;

const _uri = params.uri || '/graphql';
const middlewares = [];
const batchedMiddlewares = [];
const afterwares = [];
const batchedAfterwares = [];


const applyMiddlewares = (
requestAndOptions: RequestAndOptions | RequestsAndOptions,
batched: boolean,
Expand All @@ -95,7 +105,10 @@ export function createApolloFetch(params: FetchOptions = {}): ApolloFetch {
});
};

const applyAfterwares = (responseObject: ResponseAndOptions, batched: boolean): Promise<ResponseAndOptions> => {
const applyAfterwares = (
responseObject: ResponseAndOptions,
batched: boolean,
): Promise<ResponseAndOptions> => {
return new Promise((resolve, reject) => {
if (batched) {
buildWareStack([...batchedAfterwares], responseObject, resolve);
Expand All @@ -105,103 +118,119 @@ export function createApolloFetch(params: FetchOptions = {}): ApolloFetch {
});
};

const apolloFetch: ApolloFetch = <ApolloFetch>Object.assign(
function (request: GraphQLRequest | GraphQLRequest[]): Promise<FetchResult | FetchResult[]> {
let options = {};
let parseError;
const apolloFetch = function(
request: GraphQLRequest | GraphQLRequest[],
): Promise<FetchResult | FetchResult[]> {
let options = {};
let parseError;

const batched = Array.isArray(request);
const batched = Array.isArray(request);

const requestObject = <RequestAndOptions | RequestsAndOptions>(batched ? {
requests: request,
options,
} : {
request,
options,
});
const requestObject = <RequestAndOptions | RequestsAndOptions>(batched
? {
requests: request,
options,
}
: {
request,
options,
});

return applyMiddlewares(requestObject, batched)
.then((reqOpts) => {
const construct = (constructOptions || constructDefaultOptions);
const requestOrRequests = ((<RequestAndOptions>reqOpts).request || (<RequestsAndOptions>reqOpts).requests);
return construct(requestOrRequests, reqOpts.options);
})
.then( opts => {
options = {...opts};
return (customFetch || fetch) (_uri, options);
})
.then( response => response.text().then( raw => {
return applyMiddlewares(requestObject, batched)
.then(reqOpts => {
const construct = constructOptions || constructDefaultOptions;
const requestOrRequests =
(<RequestAndOptions>reqOpts).request ||
(<RequestsAndOptions>reqOpts).requests;
return construct(requestOrRequests, reqOpts.options);
})
.then(opts => {
options = { ...opts };
return (customFetch || fetch)(_uri, options);
})
.then(
response =>
response.text().then(raw => {
try {
const parsed = JSON.parse(raw);
return <ParsedResponse>{ ...response, raw, parsed };
(response as ParsedResponse).raw = raw;
(response as ParsedResponse).parsed = parsed;
return <ParsedResponse>response;
} catch (e) {
parseError = e;

//pass parsed raw response onto afterware
return <ParsedResponse>{ ...response, raw };
(response as ParsedResponse).raw = raw;
return <ParsedResponse>response;
}
}),
//.catch() this should never happen: https://developer.mozilla.org/en-US/docs/Web/API/Body/text
)
.then(response => applyAfterwares({
response,
options,
}, batched))
.then(({ response }) => {
if (response.parsed) {
if (batched) {
if (Array.isArray(response.parsed)) {
return response.parsed as FetchResult[];
} else {
throwBatchError(response);
}
//.catch() this should never happen: https://developer.mozilla.org/en-US/docs/Web/API/Body/text
)
.then(response =>
applyAfterwares(
{
response,
options,
},
batched,
),
)
.then(({ response }) => {
if (response.parsed) {
if (batched) {
if (Array.isArray(response.parsed)) {
return response.parsed as FetchResult[];
} else {
return { ...response.parsed };
throwBatchError(response);
}
} else {
throwHttpError(response, parseError);
return { ...response.parsed };
}
});
},
{
use: (middleware: MiddlewareInterface) => {
if (typeof middleware === 'function') {
middlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
throwHttpError(response, parseError);
}
});
};

return apolloFetch;
},
useAfter: (afterware: AfterwareInterface) => {
if (typeof afterware === 'function') {
afterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}
(apolloFetch as any).use = (middleware: MiddlewareInterface) => {
if (typeof middleware === 'function') {
middlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
}

return apolloFetch;
},
batchUse: (middleware: BatchMiddlewareInterface) => {
if (typeof middleware === 'function') {
batchedMiddlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
}
return apolloFetch;
};

return apolloFetch;
},
batchUseAfter: (afterware: BatchAfterwareInterface) => {
if (typeof afterware === 'function') {
batchedAfterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}
(apolloFetch as any).useAfter = (afterware: AfterwareInterface) => {
if (typeof afterware === 'function') {
afterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}

return apolloFetch;
},
},
);
return apolloFetch;
};

(apolloFetch as any).batchUse = (middleware: BatchMiddlewareInterface) => {
if (typeof middleware === 'function') {
batchedMiddlewares.push(middleware);
} else {
throw new Error('Middleware must be a function');
}

return apolloFetch;
};

(apolloFetch as any).batchUseAfter = (afterware: BatchAfterwareInterface) => {
if (typeof afterware === 'function') {
batchedAfterwares.push(afterware);
} else {
throw new Error('Afterware must be a function');
}

return apolloFetch;
};

return apolloFetch as ApolloFetch;
}
Loading