Skip to content

Commit

Permalink
fix: fix react-query code-gen and improve mutation options merging (z…
Browse files Browse the repository at this point in the history
  • Loading branch information
ymc9 authored Mar 31, 2023
1 parent 21ccddb commit 51484a7
Show file tree
Hide file tree
Showing 15 changed files with 75 additions and 52 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zenstack-monorepo",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "",
"scripts": {
"build": "pnpm -r build",
Expand Down
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/language",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"displayName": "ZenStack modeling language compiler",
"description": "ZenStack modeling language compiler",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/next/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/next",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"displayName": "ZenStack Next.js integration",
"description": "ZenStack Next.js integration",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/openapi",
"displayName": "ZenStack Plugin and Runtime for OpenAPI",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "ZenStack plugin and runtime supporting OpenAPI",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/react/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/react",
"displayName": "ZenStack plugin and runtime for ReactJS",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "ZenStack plugin and runtime for ReactJS",
"main": "index.js",
"repository": {
Expand Down
10 changes: 6 additions & 4 deletions packages/plugins/react/src/generator/react-query.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DMMF } from '@prisma/generator-helper';
import { getDataModels, PluginError, PluginOptions } from '@zenstackhq/sdk';
import { DataModel, Model } from '@zenstackhq/sdk/ast';
import { paramCase, pascalCase } from 'change-case';
import { camelCase, paramCase, pascalCase } from 'change-case';
import * as path from 'path';
import { Project, SourceFile, VariableDeclarationKind } from 'ts-morph';

Expand Down Expand Up @@ -71,7 +71,9 @@ function generateQueryHook(

func.addStatements([
'const { endpoint } = useContext(RequestHandlerContext);',
`return request.query<${returnType}>('${model}', \`\${endpoint}/${model}/${operation}\`, args, options);`,
`return request.query<${returnType}>('${model}', \`\${endpoint}/${camelCase(
model
)}/${operation}\`, args, options);`,
]);
}

Expand Down Expand Up @@ -117,7 +119,7 @@ function generateMutationHook(
initializer: `
request.${httpVerb}Mutation<${argsType}, ${
overrideReturnType ?? model
}>('${model}', \`\${endpoint}/${model}/${operation}\`, options, invalidateQueries)
}>('${model}', \`\${endpoint}/${camelCase(model)}/${operation}\`, options, invalidateQueries)
`,
},
],
Expand Down Expand Up @@ -173,7 +175,7 @@ function generateModelHooks(project: Project, outDir: string, model: DataModel,

// createMany
if (mapping.createMany) {
generateMutationHook(sf, model.name, 'createMany', 'post');
generateMutationHook(sf, model.name, 'createMany', 'post', 'Prisma.BatchPayload');
}

// findMany
Expand Down
87 changes: 54 additions & 33 deletions packages/plugins/react/src/runtime/react-query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useMutation, UseMutationOptions, useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query';
import {
useMutation,
useQuery,
useQueryClient,
type MutateFunction,
type QueryClient,
type UseMutationOptions,
type UseQueryOptions,
} from '@tanstack/react-query';
import { marshal, registerSerializers } from '../serialization-utils';
import { fetcher, makeUrl } from './utils';

Expand Down Expand Up @@ -43,19 +51,17 @@ export function postMutation<T, R = any>(
invalidateQueries = true
) {
const queryClient = useQueryClient();
const mutation = useMutation<R, unknown, T>({
mutationFn: (data: any) =>
fetcher<R>(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
}),
...options,
onSuccess: invalidateQueries ? () => queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]) : undefined,
});
const mutationFn = (data: any) =>
fetcher<R>(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
});

const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
const mutation = useMutation<R, unknown, T>(finalOptions);
return mutation;
}

Expand All @@ -75,19 +81,17 @@ export function putMutation<T, R = any>(
invalidateQueries = true
) {
const queryClient = useQueryClient();
const mutation = useMutation<R, unknown, T>({
mutationFn: (data: any) =>
fetcher<R>(url, {
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
}),
...options,
onSuccess: invalidateQueries ? () => queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]) : undefined,
});
const mutationFn = (data: any) =>
fetcher<R>(url, {
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: marshal(data),
});

const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
const mutation = useMutation<R, unknown, T>(finalOptions);
return mutation;
}

Expand All @@ -107,14 +111,31 @@ export function deleteMutation<T, R = any>(
invalidateQueries = true
) {
const queryClient = useQueryClient();
const mutation = useMutation<R, unknown, T>({
mutationFn: (data: any) =>
fetcher<R>(makeUrl(url, data), {
method: 'DELETE',
}),
...options,
onSuccess: invalidateQueries ? () => queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]) : undefined,
});
const mutationFn = (data: any) =>
fetcher<R>(makeUrl(url, data), {
method: 'DELETE',
});

const finalOptions = mergeOptions<T, R>(model, options, invalidateQueries, mutationFn, queryClient);
const mutation = useMutation<R, unknown, T>(finalOptions);
return mutation;
}

function mergeOptions<T, R = any>(
model: string,
options: Omit<UseMutationOptions<R, unknown, T, unknown>, 'mutationFn'> | undefined,
invalidateQueries: boolean,
mutationFn: MutateFunction<R, unknown, T>,
queryClient: QueryClient
): UseMutationOptions<R, unknown, T, unknown> {
const result = { ...options, mutationFn };
if (options?.onSuccess || invalidateQueries) {
result.onSuccess = (...args) => {
if (invalidateQueries) {
queryClient.invalidateQueries([QUERY_KEY_PREFIX + model]);
}
return options?.onSuccess?.(...args);
};
}
return result;
}
2 changes: 1 addition & 1 deletion packages/plugins/trpc/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/trpc",
"displayName": "ZenStack plugin for tRPC",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "ZenStack plugin for tRPC",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/runtime",
"displayName": "ZenStack Runtime Library",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "Runtime of ZenStack for both client-side and server-side environments.",
"repository": {
"type": "git",
Expand Down
4 changes: 2 additions & 2 deletions packages/runtime/src/enhancements/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export function makeProxy<T extends PrismaProxyHandler>(
name = 'unnamed_enhancer',
inTransaction = false
) {
const models = Object.keys(modelMeta.fields);
const models = Object.keys(modelMeta.fields).map((k) => k.toLowerCase());
const proxy = new Proxy(prisma, {
get: (target: any, prop: string | symbol, receiver: any) => {
// enhancer metadata
Expand Down Expand Up @@ -206,7 +206,7 @@ export function makeProxy<T extends PrismaProxyHandler>(
}
}

if (typeof prop !== 'string' || prop.startsWith('$') || !models.includes(prop)) {
if (typeof prop !== 'string' || prop.startsWith('$') || !models.includes(prop.toLowerCase())) {
// skip non-model fields
return Reflect.get(target, prop, receiver);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"publisher": "zenstack",
"displayName": "ZenStack Language Tools",
"description": "A toolkit for building secure CRUD apps with Next.js + Typescript",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"author": {
"name": "ZenStack Team"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/sdk",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "ZenStack plugin development SDK",
"main": "index.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/server",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"displayName": "ZenStack Server-side Adapters",
"description": "ZenStack server-side adapters",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/testtools/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/testtools",
"version": "1.0.0-alpha.94",
"version": "1.0.0-alpha.95",
"description": "ZenStack Test Tools",
"main": "index.js",
"publishConfig": {
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test-run/package-lock.json

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

0 comments on commit 51484a7

Please sign in to comment.