在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):apollographql/apollo-fetch开源软件地址(OpenSource Url):https://github.com/apollographql/apollo-fetch开源编程语言(OpenSource Language):TypeScript 98.9%开源软件介绍(OpenSource Introduction):DEPRECATEDApollo Client 2.0 no longer uses This module is deprecated and will not receive further updates. apollo-fetch
By default If you are interested in contributing, please read the documentation on repository structure and Contributor Guide. Installation
To use UsageTo create a fetch function capable of supporting middleware and afterware, use import { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri }); To execute the fetch function, call apolloFetch({ query, variables, operationName }) //all apolloFetch arguments are optional
.then(result => {
const { data, errors, extensions } = result;
//GraphQL errors and extensions are optional
})
.catch(error => {
//respond to a network error
}); Middleware and AfterwareMiddleware and Afterware are added with const apolloFetch = createApolloFetch();
const middleware = ({ request, options }, next) => { ... next(); };
const afterware = ({ response, options }, next) => { ... next(); };
apolloFetch.use(middleware);
apolloFetch.useAfter(afterware); Middleware and Afterware can be chained together in any order: const apolloFetch = createApolloFetch();
apolloFetch
.use(middleware1)
.use(middleware2)
.useAfter(afterware1)
.useAfter(afterware2)
.use(middleware3); Custom FetchFor mocking and other fetching behavior, you may pass a fetch into const customFetch = createFileFetch();
const apolloFetch = createApolloFetch({ customFetch }); Custom GraphQL to Fetch TranslationTo modify how GraphQL requests are incorporated in the fetch options, you may pass a transformation function into //requestOrRequests: GraphQLRequest | GraphQLRequest[]
//options: RequestInit
const constructOptions = (requestOrRequests, options) => {
return {
...options,
body: JSON.stringify(requestOrRequests),
}
};
const apolloFetch = createApolloFetch({ constructOptions });
//simplified usage inside apolloFetch
fetch(uri, constructOptions(requestOrRequests, options)); //requestOrRequests and options are the results from middleware Batched RequestsBatched requests are also supported by the fetch function returned by ExamplesSimple GraphQL Queryimport { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const query = `
query CurrentUser {
currentUser {
login,
}
}
`
const apolloFetch = createApolloFetch({ uri });
apolloFetch({ query }).then(...).catch(...); Simple GraphQL Mutation with Variablesimport { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const query = `
mutation SubmitRepo ($repoFullName: String!) {
submitRepository (repoFullName: $repoFullName) {
id,
score,
}
}
`;
const variables = {
repoFullName: 'apollographql/apollo-fetch',
};
const apolloFetch = createApolloFetch({ uri });
apolloFetch({ query, variables }).then(...).catch(...); MiddlewareA GraphQL mutation with authentication middleware. Middleware has access to the GraphQL query and the options passed to fetch. import { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri });
apolloFetch.use(({ request, options }, next) => {
if (!options.headers) {
options.headers = {}; // Create the headers object if needed.
}
options.headers['authorization'] = 'created token';
next();
});
apolloFetch(...).then(...).catch(...); AfterwareAfterware to check the response status and logout on a 401. The afterware has access to the raw reponse always and parsed response when the data is proper JSON. import { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri });
apolloFetch.useAfter(({ response }, next) => {
if (response.status === 401) {
logout();
}
next();
});
apolloFetch(...).then(...).catch(...); Mocking a Fetch CallThis example uses a custom fetch to mock an unauthorized(401) request with a non-standard response body.
const customFetch = () => new Promise((resolve, reject) => {
const init = {
status: 401,
statusText: 'Unauthorized',
};
const body = JSON.stringify({
data: {
user: null,
}
});
resolve(new Response(body, init));
}
const apolloFetch = createApolloFetch({ customFetch }); Error HandlingAll responses are passed to the afterware regardless of the http status code.
Network errors, This example shows an afterware that can receive a 401 with an unparsable response and return a valid import { createApolloFetch } from 'apollo-fetch';
const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri });
apolloFetch.useAfter(({ response }, next) => {
//response.raw will be a non-null string
//response.parsed may be a FetchResult or undefined
if (response.status === 401 && !response.parsed) {
//set parsed response to valid FetchResult
response.parsed = {
data: { user: null },
};
}
next();
});
//Here catch() receives all responses with unparsable data
apolloFetch(...).then(...).catch(...); Apollo Integration
import ApolloClient from 'apollo-client';
import { createApolloFetch } from 'apollo-fetch';
import { print } from 'graphql/language/printer';
const uri = 'http://api.githunt.com/graphql';
const apolloFetch = createApolloFetch({ uri });
const networkInterface = {
query: (req) => apolloFetch({...req, query: print(req.query)}),
};
const client = new ApolloClient({
networkInterface,
}); API
createApolloFetch(options: FetchOptions): ApolloFetch
FetchOptions {
uri?: string;
customFetch?: (request: RequestInfo, init: RequestInit) => Promise<Response>;
constructOptions?: (requestOrRequests: GraphQLRequest | GraphQLRequest[], options: RequestInit) => RequestInit;
}
/*
* defaults:
* uri = '/graphql'
* customFetch = fetch from cross-fetch
* constructOptions = constructDefaultOptions(exported from apollo-fetch)
*/
ApolloFetch {
(operation: GraphQLRequest): Promise<FetchResult>;
use: (middlewares: MiddlewareInterface) => ApolloFetch;
useAfter: (afterwares: AfterwareInterface) => ApolloFetch;
//Batched requests are described in the docs/batch.md
(operation: GraphQLRequest[]): Promise<FetchResult[]>;
batchUse: (middlewares: BatchMiddlewareInterface) => ApolloFetch;
batchUseAfter: (afterwares: BatchAfterwareInterface) => ApolloFetch;
}
GraphQLRequest {
query?: string;
variables?: object;
operationName?: string;
}
FetchResult {
data: any;
errors?: any;
extensions?: any;
} Middleware used by MiddlewareInterface: (request: RequestAndOptions, next: Function) => void
RequestAndOptions {
request: GraphQLRequest;
options: RequestInit;
} Afterware used by AfterwareInterface: (response: ResponseAndOptions, next: Function) => void
ResponseAndOptions {
response: ParsedResponse;
options: RequestInit;
}
ParsedResponse extends Response {
raw: string;
parsed?: any;
} A FetchError extends Error {
response: ParsedResponse;
parseError?: Error;
} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论