73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
// Copyright 2022 The Matrix.org Foundation C.I.C.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
import {
|
|
Environment,
|
|
Network,
|
|
RecordSource,
|
|
Store,
|
|
Variables,
|
|
RequestParameters,
|
|
CacheConfig,
|
|
} from "relay-runtime";
|
|
|
|
async function fetchRelay(
|
|
params: RequestParameters,
|
|
variables: Variables,
|
|
_cacheConfig: CacheConfig
|
|
) {
|
|
const response = await fetch("/graphql", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
query: params.text,
|
|
variables,
|
|
}),
|
|
});
|
|
|
|
// Get the response as JSON
|
|
const json = await response.json();
|
|
|
|
// GraphQL returns exceptions (for example, a missing required variable) in the "errors"
|
|
// property of the response. If any exceptions occurred when processing the request,
|
|
// throw an error to indicate to the developer what went wrong.
|
|
if (Array.isArray(json.errors)) {
|
|
console.log(json.errors);
|
|
throw new Error(
|
|
`Error fetching GraphQL query '${
|
|
params.name
|
|
}' with variables '${JSON.stringify(variables)}': ${JSON.stringify(
|
|
json.errors
|
|
)}`
|
|
);
|
|
}
|
|
|
|
// Otherwise, return the full payload.
|
|
return json;
|
|
}
|
|
|
|
// Export a singleton instance of Relay Environment configured with our network layer:
|
|
export default new Environment({
|
|
network: Network.create(fetchRelay),
|
|
store: new Store(new RecordSource(), {
|
|
// This property tells Relay to not immediately clear its cache when the user
|
|
// navigates around the app. Relay will hold onto the specified number of
|
|
// query results, allowing the user to return to recently visited pages
|
|
// and reusing cached data if its available/fresh.
|
|
gcReleaseBufferSize: 10,
|
|
}),
|
|
});
|