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

feat: add multipart subscription network adapters for Relay and urql #11301

Merged
merged 7 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
46 changes: 46 additions & 0 deletions .changeset/strong-terms-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
"@apollo/client": minor
---

Add multipart subscription network adapters for Relay and urql

### Relay

```tsx
import { createFetchMultipartSubscription } from "@apollo/client/utilities/subscriptions/relay";
import { Environment, Network, RecordSource, Store } from "relay-runtime";

const fetchMultipartSubs = createFetchMultipartSubscription(
"http://localhost:4000"
);

const network = Network.create(fetchQuery, fetchMultipartSubs);

export const RelayEnvironment = new Environment({
network,
store: new Store(new RecordSource()),
});
```

### Urql

```tsx
import { createFetchMultipartSubscription } from "@apollo/client/utilities/subscriptions/urql";
import { Client, fetchExchange, subscriptionExchange } from "@urql/core";

const url = "http://localhost:4000";

const multipartSubscriptionForwarder = createFetchMultipartSubscription(
url
);

const client = new Client({
url,
exchanges: [
fetchExchange,
subscriptionExchange({
forwardSubscription: multipartSubscriptionForwarder,
}),
],
});
```
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"@types/node-fetch": "2.6.6",
"@types/react": "18.2.28",
"@types/react-dom": "18.2.13",
"@types/relay-runtime": "14.1.14",
"@types/use-sync-external-store": "0.0.4",
"@typescript-eslint/eslint-plugin": "6.7.5",
"@typescript-eslint/parser": "6.7.5",
Expand Down
60 changes: 60 additions & 0 deletions src/utilities/subscriptions/relay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Observable } from "relay-runtime";
import type { RequestParameters, GraphQLResponse } from "relay-runtime";
import {
handleError,
readMultipartBody,
} from "../../link/http/parseAndCheckHttpResponse.js";
import { maybe } from "../index.js";
import { serializeFetchParameter } from "../../core/index.js";

import type { OperationVariables } from "../../core/index.js";
import type { Body } from "../../link/http/selectHttpOptionsAndBody.js";
import { generateOptionsForMultipartSubscription } from "./shared.js";
import type { CreateMultipartSubscriptionOptions } from "./shared.js";

const backupFetch = maybe(() => fetch);

export function createFetchMultipartSubscription(
uri: string,
{ fetch: preferredFetch, headers }: CreateMultipartSubscriptionOptions = {}
) {
return function fetchMultipartSubscription(
operation: RequestParameters,
variables: OperationVariables
): Observable<GraphQLResponse> {
const body: Body = {
operationName: operation.name,
variables,
query: operation.text || "",
};
const options = generateOptionsForMultipartSubscription(headers || {});

return Observable.create((sink) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

zen-observable-ts's Observable is incompatible with Relay's networking API here, so I'm using the relay-runtime's Observable. (Using the former produces a network.execute(...).do is not a function error.)

A related note about project dependencies: I added @types/relay-runtime to our dev dependencies, but did not specify relay-runtime as an optional peer dependency. The risk of confusing a lot of people seemed to outweigh the chance at a mild annoyance if someone were to try to drop in this subscriptions network layer without already having relay-runtime installed :)

try {
options.body = serializeFetchParameter(body, "Payload");
} catch (parseError) {
sink.error(parseError);
}

const currentFetch = preferredFetch || maybe(() => fetch) || backupFetch;
const observerNext = sink.next.bind(sink);

currentFetch!(uri, options)
.then((response) => {
const ctype = response.headers?.get("content-type");

if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}

sink.error(new Error("Expected multipart response"));
})
.then(() => {
sink.complete();
})
.catch((err: any) => {
handleError(err, sink);
});
});
};
}
21 changes: 21 additions & 0 deletions src/utilities/subscriptions/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { fallbackHttpConfig } from "../../link/http/selectHttpOptionsAndBody.js";

export type CreateMultipartSubscriptionOptions = {
fetch?: WindowOrWorkerGlobalScope["fetch"];
headers?: Record<string, string>;
};

export function generateOptionsForMultipartSubscription(
headers: Record<string, string>
) {
const options: { headers: Record<string, any>; body?: string } = {
...fallbackHttpConfig.options,
headers: {
...(headers || {}),
...fallbackHttpConfig.headers,
accept:
"multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json",
},
};
return options;
}
56 changes: 56 additions & 0 deletions src/utilities/subscriptions/urql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Observable } from "../index.js";
import {
handleError,
readMultipartBody,
} from "../../link/http/parseAndCheckHttpResponse.js";
import { maybe } from "../index.js";
import { serializeFetchParameter } from "../../core/index.js";
import type { Body } from "../../link/http/selectHttpOptionsAndBody.js";
import { generateOptionsForMultipartSubscription } from "./shared.js";
import type { CreateMultipartSubscriptionOptions } from "./shared.js";

const backupFetch = maybe(() => fetch);

export function createFetchMultipartSubscription(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I used the same function name here but maybe this should be a more urql-y createMultipartSubscriptionForwarder

uri: string,
{ fetch: preferredFetch, headers }: CreateMultipartSubscriptionOptions = {}
) {
return function multipartSubscriptionForwarder({
query,
variables,
}: {
query?: string;
variables: undefined | Record<string, any>;
}) {
const body: Body = { variables, query };
const options = generateOptionsForMultipartSubscription(headers || {});

return new Observable((observer) => {
try {
options.body = serializeFetchParameter(body, "Payload");
} catch (parseError) {
observer.error(parseError);
}

const currentFetch = preferredFetch || maybe(() => fetch) || backupFetch;
const observerNext = observer.next.bind(observer);

currentFetch!(uri, options)
.then((response) => {
const ctype = response.headers?.get("content-type");

if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}

observer.error(new Error("Expected multipart response"));
})
.then(() => {
observer.complete();
})
.catch((err: any) => {
handleError(err, observer);
});
});
};
}
Loading