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

Create Relay Environment package #123

Merged
merged 3 commits into from
Feb 20, 2024
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
1 change: 1 addition & 0 deletions packages/relay-environment/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
1 change: 1 addition & 0 deletions packages/relay-environment/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.turbo
2 changes: 2 additions & 0 deletions packages/relay-environment/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
node_modules
27 changes: 27 additions & 0 deletions packages/relay-environment/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# @spear-ai/relay-environment

General purpose [Relay Environment](https://relay.dev).

## Installation

```shell
yarn add relay-runtime @spear-ai/relay-environment
```

## Usage

Add the following to your React Relay Provider:

```tsx
import { createEnvironment } from "@spear-ai/relay-environment";
import React, { useMemo } from "react";
import { RelayEnvironmentProvider } from "react-relay";

const apiUrl = "/api/graphql";
const environment = createEnvironment({ apiUrl });

export const RelayProvider = (properties: { children: JSX.Element }) => {
const { children } = properties;
return <RelayEnvironmentProvider environment={environment}>{children}</RelayEnvironmentProvider>;
};
```
12 changes: 12 additions & 0 deletions packages/relay-environment/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { baseEslintConfig, prettierConfig } from "@spear-ai/eslint-config";

/** @type {import("eslint").Linter.FlatConfig} */
const eslintConfig = [
{
ignores: ["dist", "node_modules"],
},
...baseEslintConfig,
prettierConfig,
];

export default eslintConfig;
6 changes: 6 additions & 0 deletions packages/relay-environment/npmpackagejsonlint.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
extends: ["@spear-ai/npm-package-json-lint-config/spear-library"],
rules: {
"prefer-absolute-version-devDependencies": "off",
},
};
50 changes: 50 additions & 0 deletions packages/relay-environment/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "@spear-ai/relay-environment",
"version": "1.0.0",
"description": "Spear AI Relay Environment",
"author": {
"name": "Spear AI",
"email": "[email protected]",
"url": "https://spear.ai"
},
"type": "module",
"devDependencies": {
"@spear-ai/eslint-config": "17.1.0",
"@spear-ai/npm-package-json-lint-config": "3.1.0",
"@spear-ai/prettier-config": "2.1.0",
"@types/relay-runtime": "14.1.23",
"autoprefixer": "10.4.17",
"eslint": "8.56.0",
"graphql": "16.8.1",
"npm-package-json-lint": "7.1.0",
"prettier": "3.2.5",
"react": "18.2.0",
"react-relay": "16.2.0",
"relay-runtime": "16.2.0",
"tailwindcss": "3.4.1",
"tsup": "8.0.2",
"typescript": "5.3.3"
},
"license": "MIT",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"peerDependencies": {
"relay-runtime": "^16.2.0"
},
"repository": {
"type": "git",
"directory": "packages/relay-environment",
"url": "https://github.com/spear-ai/ui.git"
},
"scripts": {
"build": "tsup src --clean --dts --format cjs,esm",
"dev": "yarn run build --watch",
"eslint:check": "eslint --max-warnings 0 .",
"eslint:fix": "yarn eslint:check --fix",
"npmpkgjsonlint:check": "npmPkgJsonLint .",
"prettier:check": "prettier --check .",
"prettier:fix": "prettier --write .",
"typescript:check": "tsc --noEmit"
},
"types": "./dist/index.d.ts"
}
108 changes: 108 additions & 0 deletions packages/relay-environment/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import {
CacheConfig,
Environment,
GraphQLResponse,
Network,
QueryResponseCache,
RecordSource,
RequestParameters,
Store,
Variables,
} from "relay-runtime";

const networkFetch = async (
request: RequestParameters,
variables: Variables,
apiUrl: string,
): Promise<GraphQLResponse> => {
const response = await fetch(apiUrl, {
body: JSON.stringify({
query: request.text,
variables,
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
method: "POST",
});

return (await response.json()) as unknown as GraphQLResponse;
};

const createFetchResponse = (options: {
apiUrl: string;
cacheSize: number;
cacheTtl: number;
latencyRetentionCount: number;
recentFetchLatencyList: number[];
}) => {
const { apiUrl, cacheSize, cacheTtl, latencyRetentionCount, recentFetchLatencyList } = options;

const responseCache: QueryResponseCache = new QueryResponseCache({
size: cacheSize,
ttl: cacheTtl,
});

return async (parameters: RequestParameters, variables: Variables, cacheConfig: CacheConfig) => {
const isQuery = parameters.operationKind === "query";
const cacheKey = parameters.id ?? parameters.cacheID;
const forceFetch = cacheConfig.force;

if (isQuery && !forceFetch) {
const fromCache = responseCache.get(cacheKey, variables);

if (fromCache != null) {
return fromCache;
}
}

const fetchStart = performance.now();
const fetchResult = await networkFetch(parameters, variables, apiUrl);
const fetchEnd = performance.now();

recentFetchLatencyList.push(fetchEnd - fetchStart);

if (recentFetchLatencyList.length > latencyRetentionCount) {
recentFetchLatencyList.shift();
}

return fetchResult;
};
};

export type RelayEnvironment = Environment & {
options: {
/** The most recent fetch latency metrics. */
recentFetchLatencyList: number[];
};
};

export const createEnvironment = (options: {
/** The GraphQL API URL. */
apiUrl: string;
/** The maximum number of entities to keep inside Relay’s cache. */
cacheSize?: number | undefined;
/** The maximum time to keep entities inside Relay’s cache. */
cacheTtl?: number | undefined;
/** The maximum number of latency metrics to retain. */
latencyRetentionCount?: number | undefined;
}): RelayEnvironment => {
const { apiUrl, cacheSize = 100, cacheTtl = 5000, latencyRetentionCount = 100 } = options;
const recentFetchLatencyList: number[] = [];

return new Environment({
isServer: false,
network: Network.create(
createFetchResponse({
apiUrl,
cacheSize,
cacheTtl,
latencyRetentionCount,
recentFetchLatencyList,
}),
),
options: { recentFetchLatencyList },
store: new Store(RecordSource.create()),
}) as RelayEnvironment;
};
32 changes: 32 additions & 0 deletions packages/relay-environment/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"compilerOptions": {
"declaration": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"outDir": "bin",
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"stripInternal": true,
"target": "ESNext"
},
"exclude": ["node_modules"],
"include": [
"**/*.cjs",
"**/*.cts",
"**/*.js",
"<tsconfigRootDir>//README.md/1_1.js",
"**/*.mjs",
"**/*.mts",
"**/*.ts",
"types"
]
}
4 changes: 4 additions & 0 deletions workspace.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
"name": "spear-ai",
"path": ".",
},
{
"name": "spear-ai/relay-environment",
"path": "packages/relay-environment",
},
{
"name": "spear-ai/tailwind-config",
"path": "packages/tailwind-config",
Expand Down
Loading
Loading