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

Preserve body on request object passed to willSendRequest; fix string and Buffer body handling #89

Merged
merged 19 commits into from
Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from 18 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
12 changes: 12 additions & 0 deletions .changeset/cuddly-cars-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@apollo/datasource-rest': major
---

This change restores the full functionality of `willSendRequest` which
previously existed in the v3 version of this package. The v4 change introduced a
regression where the incoming request's `body` was no longer included in the
object passed to the `willSendRequest` hook, it was always `undefined`.

For consistency and typings reasons, the `path` argument is now the first
argument to the `willSendRequest` hook, followed by the `AugmentedRequest`
request object.
8 changes: 8 additions & 0 deletions .changeset/tidy-spoons-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@apollo/datasource-rest': patch
---

`string` and `Buffer` bodies are now correctly included on the outgoing request.
Due to a regression in v4, they were ignored and never appended to the `body`.
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
`string` and `Buffer` bodies are now passed through to the outgoing request
(without being JSON stringified).
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,12 @@ By default, `RESTDatasource` uses the full request URL as the cache key. Overrid
For example, you could use this to use header fields as part of the cache key. Even though we do validate header fields and don't serve responses from cache when they don't match, new responses overwrite old ones with different header fields.

##### `willSendRequest`
This method is invoked just before the fetch call is made. If a `Promise` is returned from this method it will wait until the promise is completed to continue executing the request.
This method is invoked immediately after `fetch` is called (or any of the
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
convenience functions which call it like `.get()`). It's called with the `path`
and `request` provided to `fetch`, with a guaranteed non-empty `headers` and
`params` objects. If a `Promise` is returned from this method it will wait until
the promise is completed to continue executing the request. See the
[intercepting fetches](#intercepting-fetches) section for usage examples.

##### `cacheOptionsFor`
Allows setting the `CacheOptions` to be used for each request/response in the HTTPCache. This is separate from the request-only cache. You can use this to set the TTL.
Expand Down Expand Up @@ -180,7 +185,7 @@ You can easily set a header on every request:

```javascript
class PersonalizationAPI extends RESTDataSource {
willSendRequest(request) {
willSendRequest(path, request) {
request.headers['authorization'] = this.context.token;
}
}
Expand All @@ -190,15 +195,15 @@ Or add a query parameter:

```javascript
class PersonalizationAPI extends RESTDataSource {
willSendRequest(request) {
willSendRequest(path, request) {
request.params.set('api_key', this.context.token);
}
}
```

If you're using TypeScript, you can use the `RequestOptions` type to define the `willSendRequest` signature:
If you're using TypeScript, you can use the `AugmentedRequest` type to define the `willSendRequest` signature:
```ts
import { RESTDataSource, WillSendRequestOptions } from '@apollo/datasource-rest';
import { RESTDataSource, AugmentedRequest } from '@apollo/datasource-rest';

class PersonalizationAPI extends RESTDataSource {
override baseURL = 'https://personalization-api.example.com/';
Expand All @@ -207,7 +212,7 @@ class PersonalizationAPI extends RESTDataSource {
super();
}

override willSendRequest(request: WillSendRequestOptions) {
override willSendRequest(_path: string, request: AugmentedRequest) {
request.headers['authorization'] = this.token;
}
}
Expand All @@ -223,7 +228,7 @@ class PersonalizationAPI extends RESTDataSource {
super();
}

override async resolveURL(path: string) {
override async resolveURL(path: string, _request: AugmentedRequest) {
if (!this.baseURL) {
const addresses = await resolveSrv(path.split("/")[1] + ".service.consul");
this.baseURL = addresses[0];
Expand Down
97 changes: 56 additions & 41 deletions src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,6 @@ export type RequestOptions = FetcherRequestInit & {
) => CacheOptions | undefined);
};

export type WillSendRequestOptions = Omit<
WithRequired<RequestOptions, 'headers'>,
'params'
> & {
params: URLSearchParams;
};

export interface GetRequest extends RequestOptions {
method?: 'GET';
body?: never;
Expand All @@ -48,6 +41,23 @@ export interface RequestWithBody extends Omit<RequestOptions, 'body'> {

type DataSourceRequest = GetRequest | RequestWithBody;

/**
* While tempting, this union can't be reduced / factored out to just
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
* Omit<WithRequired<GetRequest | RequestWithBody, 'headers'>, 'params'> & {
* params: URLSearchParams } TS loses its ability to discriminate against the
* method (and its consequential `body` type)
*
* This type is for convenience w.r.t. the `willSendRequest` and `resolveURL`
* hooks to ensure that headers and params are always present, even if they're
* empty.
*/
export type AugmentedRequest = (
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be worth a comment that the point here is basically, this is like DataSourceRequest but with headers and params normalized for convenience in your callbacks.

BTW unrelated but it seems like method shouldn't be optional in GetRequest/RequestWithBody?

| Omit<WithRequired<GetRequest, 'headers'>, 'params'>
| Omit<WithRequired<RequestWithBody, 'headers'>, 'params'>
) & {
params: URLSearchParams;
};

export interface CacheOptions {
ttl?: number;
}
Expand Down Expand Up @@ -79,12 +89,13 @@ export abstract class RESTDataSource {
}

protected willSendRequest?(
requestOpts: WillSendRequestOptions,
path: string,
requestOpts: AugmentedRequest,
): ValueOrPromise<void>;

protected resolveURL(
path: string,
_request: RequestOptions,
_request: AugmentedRequest,
): ValueOrPromise<URL> {
return new URL(path, this.baseURL);
}
Expand Down Expand Up @@ -205,71 +216,75 @@ export abstract class RESTDataSource {

private async fetch<TResult>(
path: string,
request: DataSourceRequest,
incomingRequest: DataSourceRequest,
): Promise<TResult> {
const modifiedRequest: WillSendRequestOptions = {
...request,
const augmentedRequest: AugmentedRequest = {
...incomingRequest,
// guarantee params and headers objects before calling `willSendRequest` for convenience
params:
request.params instanceof URLSearchParams
? request.params
: this.urlSearchParamsFromRecord(request.params),
headers: request.headers ?? Object.create(null),
body: undefined,
incomingRequest.params instanceof URLSearchParams
? incomingRequest.params
: this.urlSearchParamsFromRecord(incomingRequest.params),
headers: incomingRequest.headers ?? Object.create(null),
};

if (this.willSendRequest) {
await this.willSendRequest(modifiedRequest);
await this.willSendRequest(path, augmentedRequest);
}

const url = await this.resolveURL(path, modifiedRequest);
const url = await this.resolveURL(path, augmentedRequest);

// Append params from the request to any existing params in the path
for (const [name, value] of modifiedRequest.params as URLSearchParams) {
// Append params to existing params in the path
for (const [name, value] of augmentedRequest.params as URLSearchParams) {
url.searchParams.append(name, value);
}

// We accept arbitrary objects and arrays as body and serialize them as JSON
// We accept arbitrary objects and arrays as body and serialize them as JSON.
// `string`, `Buffer`, and `undefined` are passed through up above as-is.
if (
request.body !== undefined &&
request.body !== null &&
(request.body.constructor === Object ||
Array.isArray(request.body) ||
((request.body as any).toJSON &&
typeof (request.body as any).toJSON === 'function'))
augmentedRequest.body != null &&
!(augmentedRequest.body instanceof Buffer) &&
(augmentedRequest.body.constructor === Object ||
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
Array.isArray(augmentedRequest.body) ||
((augmentedRequest.body as any).toJSON &&
typeof (augmentedRequest.body as any).toJSON === 'function'))
) {
modifiedRequest.body = JSON.stringify(request.body);
augmentedRequest.body = JSON.stringify(augmentedRequest.body);
// If Content-Type header has not been previously set, set to application/json
if (!modifiedRequest.headers) {
modifiedRequest.headers = { 'content-type': 'application/json' };
} else if (!modifiedRequest.headers['content-type']) {
modifiedRequest.headers['content-type'] = 'application/json';
if (!augmentedRequest.headers) {
augmentedRequest.headers = { 'content-type': 'application/json' };
} else if (!augmentedRequest.headers['content-type']) {
augmentedRequest.headers['content-type'] = 'application/json';
}
}

const cacheKey = this.cacheKeyFor(url, modifiedRequest);
// At this point we know the `body` is a `string`, `Buffer`, or `undefined`
// (not possibly an `object`).
const outgoingRequest = augmentedRequest as RequestOptions;

const cacheKey = this.cacheKeyFor(url, outgoingRequest);

const performRequest = async () => {
return this.trace(url, modifiedRequest, async () => {
const cacheOptions = modifiedRequest.cacheOptions
? modifiedRequest.cacheOptions
return this.trace(url, outgoingRequest, async () => {
const cacheOptions = outgoingRequest.cacheOptions
? outgoingRequest.cacheOptions
: this.cacheOptionsFor?.bind(this);
try {
const response = await this.httpCache.fetch(url, modifiedRequest, {
const response = await this.httpCache.fetch(url, outgoingRequest, {
cacheKey,
cacheOptions,
});
return await this.didReceiveResponse(response, modifiedRequest);
return await this.didReceiveResponse(response, outgoingRequest);
} catch (error) {
this.didEncounterError(error as Error, modifiedRequest);
this.didEncounterError(error as Error, outgoingRequest);
}
});
};

// Cache GET requests based on the calculated cache key
// Disabling the request cache does not disable the response cache
if (this.memoizeGetRequests) {
if (request.method === 'GET') {
if (outgoingRequest.method === 'GET') {
let promise = this.memoizedResults.get(cacheKey);
if (promise) return promise;

Expand Down
Loading