Skip to content
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
14 changes: 14 additions & 0 deletions packages/plugins/swr/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
]
}
1 change: 1 addition & 0 deletions packages/plugins/swr/LICENSE
5 changes: 5 additions & 0 deletions packages/plugins/swr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# ZenStack React plugin & runtime

This package contains ZenStack plugin and runtime for ReactJS.

Visit [Homepage](https://zenstack.dev) for more details.
29 changes: 29 additions & 0 deletions packages/plugins/swr/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

export default {
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,

// The directory where Jest should output its coverage files
coverageDirectory: 'tests/coverage',

// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ['/node_modules/', '/tests/'],

// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',

// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ['json', 'text', 'lcov', 'clover'],

// A map from regular expressions to paths to transformers
transform: { '^.+\\.tsx?$': 'ts-jest' },

testTimeout: 300000,
};
53 changes: 53 additions & 0 deletions packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "@zenstackhq/swr",
"displayName": "ZenStack plugin for generating SWR hooks",
"version": "1.0.0-alpha.116",
"description": "ZenStack plugin for generating SWR hooks",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/zenstackhq/zenstack"
},
"scripts": {
"clean": "rimraf dist",
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"prepublishOnly": "pnpm build",
"publish-dev": "pnpm publish --tag dev"
},
"publishConfig": {
"directory": "dist",
"linkDirectory": true
},
"keywords": [],
"author": "ZenStack Team",
"license": "MIT",
"dependencies": {
"@prisma/generator-helper": "^4.7.1",
"@zenstackhq/sdk": "workspace:*",
"change-case": "^4.1.2",
"decimal.js": "^10.4.2",
"lower-case-first": "^2.0.2",
"superjson": "^1.11.0",
"ts-morph": "^16.0.0",
"upper-case-first": "^2.0.2"
},
"devDependencies": {
"@tanstack/react-query": "^4.28.0",
"@types/jest": "^29.5.0",
"@types/lower-case-first": "^1.0.1",
"@types/react": "^18.0.26",
"@types/tmp": "^0.2.3",
"@types/upper-case-first": "^1.1.2",
"@zenstackhq/testtools": "workspace:*",
"copyfiles": "^2.4.1",
"jest": "^29.5.0",
"react": "^17.0.2 || ^18",
"react-dom": "^17.0.2 || ^18",
"rimraf": "^3.0.2",
"swr": "^2.0.3",
"ts-jest": "^29.0.5",
"typescript": "^4.9.4"
}
}
147 changes: 147 additions & 0 deletions packages/plugins/swr/res/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { createContext } from 'react';
import type { MutatorCallback, MutatorOptions, SWRResponse } from 'swr';
import useSWR, { useSWRConfig } from 'swr';

/**
* Context type for configuring react hooks.
*/
export type RequestHandlerContext = {
endpoint: string;
};

/**
* Context for configuring react hooks.
*/
export const RequestHandlerContext = createContext<RequestHandlerContext>({
endpoint: '/api/model',
});

/**
* Context provider.
*/
export const Provider = RequestHandlerContext.Provider;

/**
* Client request options
*/
export type RequestOptions<T> = {
// disable data fetching
disabled?: boolean;
initialData?: T;
};

/**
* Makes a GET request with SWR.
*
* @param url The request URL.
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
* @returns SWR response
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function get<Data, Error = any>(
url: string | null,
args?: unknown,
options?: RequestOptions<Data>
): SWRResponse<Data, Error> {
const reqUrl = options?.disabled ? null : url ? makeUrl(url, args) : null;
return useSWR<Data, Error>(reqUrl, fetcher, {
fallbackData: options?.initialData,
});
}

/**
* Makes a POST request.
*
* @param url The request URL.
* @param data The request data.
* @param mutate Mutator for invalidating cache.
*/
export async function post<Data, Result>(url: string, data: Data, mutate: Mutator): Promise<Result> {
const r: Result = await fetcher(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
});
mutate();
return r;
}

/**
* Makes a PUT request.
*
* @param url The request URL.
* @param data The request data.
* @param mutate Mutator for invalidating cache.
*/
export async function put<Data, Result>(url: string, data: Data, mutate: Mutator): Promise<Result> {
const r: Result = await fetcher(url, {
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
});
mutate();
return r;
}

/**
* Makes a DELETE request.
*
* @param url The request URL.
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
* @param mutate Mutator for invalidating cache.
*/
export async function del<Result>(url: string, args: unknown, mutate: Mutator): Promise<Result> {
const reqUrl = makeUrl(url, args);
const r: Result = await fetcher(reqUrl, {
method: 'DELETE',
});
const path = url.split('/');
path.pop();
mutate();
return r;
}

type Mutator = (
data?: unknown | Promise<unknown> | MutatorCallback,
opts?: boolean | MutatorOptions
) => Promise<unknown[]>;

export function getMutate(prefixes: string[]): Mutator {
// https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
const { cache, mutate } = useSWRConfig();
return (data?: unknown | Promise<unknown> | MutatorCallback, opts?: boolean | MutatorOptions) => {
if (!(cache instanceof Map)) {
throw new Error('mutate requires the cache provider to be a Map instance');
}

const keys = Array.from(cache.keys()).filter(
(k) => typeof k === 'string' && prefixes.some((prefix) => k.startsWith(prefix))
) as string[];
const mutations = keys.map((key) => mutate(key, data, opts));
return Promise.all(mutations);
};
}

export async function fetcher<R>(url: string, options?: RequestInit) {
const res = await fetch(url, options);
if (!res.ok) {
const error: Error & { info?: unknown; status?: number } = new Error(
'An error occurred while fetching the data.'
);
error.info = unmarshal(await res.text());
error.status = res.status;
throw error;
}

const textResult = await res.text();
try {
return unmarshal(textResult) as R;
} catch (err) {
console.error(`Unable to deserialize data:`, textResult);
throw err;
}
}
12 changes: 12 additions & 0 deletions packages/plugins/swr/res/marshal-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function marshal(value: unknown) {
return JSON.stringify(value);
}

function unmarshal(value: string) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return JSON.parse(value) as any;
}

function makeUrl(url: string, args: unknown) {
return args ? url + `?q=${encodeURIComponent(JSON.stringify(args))}` : url;
}
20 changes: 20 additions & 0 deletions packages/plugins/swr/res/marshal-superjson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import superjson from 'superjson';

function marshal(value: unknown) {
return superjson.stringify(value);
}

function unmarshal(value: string) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const j = JSON.parse(value) as any;
if (j?.json) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return superjson.parse<any>(value);
} else {
return j;
}
}

function makeUrl(url: string, args: unknown) {
return args ? url + `?q=${encodeURIComponent(superjson.stringify(args))}` : url;
}
Loading