Skip to content

Commit

Permalink
feat: implementing sveltekit adapter and refactor server package (zen…
Browse files Browse the repository at this point in the history
  • Loading branch information
ymc9 authored May 18, 2023
1 parent 9351fc9 commit 53716c9
Show file tree
Hide file tree
Showing 31 changed files with 1,057 additions and 219 deletions.
1 change: 1 addition & 0 deletions packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE 'res/**/*' dist",
"watch": "tsc --watch",
"lint": "eslint src --ext ts",
"test": "jest",
"prepublishOnly": "pnpm build",
"publish-dev": "pnpm publish --tag dev"
},
Expand Down
12 changes: 12 additions & 0 deletions packages/plugins/tanstack-query/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/tanstack-query/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;
}
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/res/react/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const Provider = RequestHandlerContext.Provider;
*
* @param model The name of the model under query.
* @param url The request URL.
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
* @param args The request args object, URL-encoded and appended as "?q=" parameter
* @param options The react-query options object
* @returns useQuery hook
*/
Expand Down
18 changes: 0 additions & 18 deletions packages/plugins/tanstack-query/res/shared.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import superjson from 'superjson';

/**
* The default query endpoint.
*/
Expand All @@ -17,13 +15,6 @@ export type RequestHandlerContext = {
endpoint: string;
};

/**
* Builds a request URL with optional args.
*/
export function makeUrl(url: string, args: unknown) {
return args ? url + `?q=${encodeURIComponent(marshal(args))}` : url;
}

async function fetcher<R>(url: string, options?: RequestInit) {
const res = await fetch(url, options);
if (!res.ok) {
Expand All @@ -43,12 +34,3 @@ async function fetcher<R>(url: string, options?: RequestInit) {
throw err;
}
}

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

export function unmarshal(value: string) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return superjson.parse<any>(value);
}
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/res/svelte/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const SvelteQueryContextKey = 'zenstack-svelte-query-context';
*
* @param model The name of the model under query.
* @param url The request URL.
* @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
* @param args The request args object, URL-encoded and appended as "?q=" parameter
* @param options The svelte-query options object
* @returns useQuery hook
*/
Expand Down
13 changes: 9 additions & 4 deletions packages/plugins/tanstack-query/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export async function generate(model: Model, options: PluginOptions, dmmf: DMMF.
}

generateIndex(project, outDir, models);
generateHelper(target, project, outDir);
generateHelper(target, project, outDir, options.useSuperJson === true);

models.forEach((dataModel) => {
const mapping = dmmf.mappings.modelOperations.find((op) => op.model === dataModel.name);
Expand Down Expand Up @@ -385,7 +385,7 @@ function generateIndex(project: Project, outDir: string, models: DataModel[]) {
sf.addStatements(`export * from './_helper';`);
}

function generateHelper(target: TargetFramework, project: Project, outDir: string) {
function generateHelper(target: TargetFramework, project: Project, outDir: string, useSuperJson: boolean) {
let srcFile: string;
switch (target) {
case 'react':
Expand All @@ -398,10 +398,15 @@ function generateHelper(target: TargetFramework, project: Project, outDir: strin
throw new PluginError(`Unsupported target: ${target}`);
}

// merge content of `shared.ts` and `helper.ts`
// merge content of `shared.ts`, `helper.ts` and `marshal-?.ts`
const sharedContent = fs.readFileSync(path.join(__dirname, './res/shared.ts'), 'utf-8');
const helperContent = fs.readFileSync(srcFile, 'utf-8');
project.createSourceFile(path.join(outDir, '_helper.ts'), `${sharedContent}\n${helperContent}`, {
const marshalContent = fs.readFileSync(
path.join(__dirname, useSuperJson ? './res/marshal-superjson.ts' : './res/marshal-json.ts'),
'utf-8'
);

project.createSourceFile(path.join(outDir, '_helper.ts'), `${sharedContent}\n${helperContent}\n${marshalContent}`, {
overwrite: true,
});
}
Expand Down
42 changes: 40 additions & 2 deletions packages/plugins/tanstack-query/tests/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ model Foo {
}
`;

it('react-query generator', async () => {
it('react-query generator regular json', async () => {
await loadSchema(
`
plugin tanstack {
Expand All @@ -49,6 +49,25 @@ plugin tanstack {
target = 'react'
}
${sharedModel}
`,
true,
false,
[`${origDir}/dist`, 'react', '@types/react', '@tanstack/react-query'],
true
);
});

it('react-query generator superjson', async () => {
await loadSchema(
`
plugin tanstack {
provider = '${process.cwd()}/dist'
output = '$projectRoot/hooks'
target = 'react'
useSuperJson = true
}
${sharedModel}
`,
true,
Expand All @@ -58,13 +77,32 @@ ${sharedModel}
);
});

it('svelte-query generator', async () => {
it('svelte-query generator regular json', async () => {
await loadSchema(
`
plugin tanstack {
provider = '${process.cwd()}/dist'
output = '$projectRoot/hooks'
target = 'svelte'
}
${sharedModel}
`,
true,
false,
[`${origDir}/dist`, 'svelte', '@types/react', '@tanstack/svelte-query'],
true
);
});

it('svelte-query generator superjson', async () => {
await loadSchema(
`
plugin tanstack {
provider = '${process.cwd()}/dist'
output = '$projectRoot/hooks'
target = 'svelte'
useSuperJson = true
}
${sharedModel}
Expand Down
3 changes: 3 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@zenstackhq/sdk": "workspace:*",
"change-case": "^4.1.2",
"lower-case-first": "^2.0.2",
"superjson": "^1.11.0",
"tiny-invariant": "^1.3.1",
"ts-japi": "^1.8.0",
"upper-case-first": "^2.0.2",
Expand All @@ -36,6 +37,7 @@
"zod-validation-error": "^0.2.1"
},
"devDependencies": {
"@sveltejs/kit": "^1.16.3",
"@types/body-parser": "^1.19.2",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.0",
Expand All @@ -48,6 +50,7 @@
"express": "^4.18.2",
"fastify": "^4.14.1",
"fastify-plugin": "^4.5.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^29.5.0",
"rimraf": "^3.0.2",
"supertest": "^6.3.3",
Expand Down
12 changes: 3 additions & 9 deletions packages/server/src/api/rest/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
DbClientContract,
FieldInfo,
Expand All @@ -16,7 +15,7 @@ import { DataDocument, Linker, Paginator, Relator, Serializer, SerializerOptions
import UrlPattern from 'url-pattern';
import z from 'zod';
import { fromZodError } from 'zod-validation-error';
import { LoggerConfig, RequestContext, Response } from '../types';
import { LoggerConfig, RequestContext, Response } from '../../types';
import { getZodSchema, logWarning, stripAuxFields } from '../utils';

const urlPatterns = {
Expand Down Expand Up @@ -320,7 +319,7 @@ class RequestHandler {
let match = urlPatterns.single.match(path);
if (match) {
// resource deletion
return await this.processDelete(prisma, match.type, match.id, query);
return await this.processDelete(prisma, match.type, match.id);
}

match = urlPatterns.relationship.match(path);
Expand Down Expand Up @@ -899,12 +898,7 @@ class RequestHandler {
}
}

private async processDelete(
prisma: DbClientContract,
type: any,
resourceId: string,
query: Record<string, string | string[]> | undefined
): Promise<Response> {
private async processDelete(prisma: DbClientContract, type: any, resourceId: string): Promise<Response> {
const typeInfo = this.typeMap[type];
if (!typeInfo) {
return this.makeUnsupportedModelError(type);
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/api/rpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
isPrismaClientValidationError,
} from '@zenstackhq/runtime';
import { ModelZodSchema } from '@zenstackhq/runtime/zod';
import { LoggerConfig, RequestContext, Response } from '../types';
import { LoggerConfig, RequestContext, Response } from '../../types';
import { logError, stripAuxFields, zodValidate } from '../utils';

/**
Expand Down
48 changes: 0 additions & 48 deletions packages/server/src/api/types.ts

This file was deleted.

16 changes: 12 additions & 4 deletions packages/server/src/api/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ModelZodSchema } from '@zenstackhq/runtime/zod';
import { upperCaseFirst } from 'upper-case-first';
import { fromZodError } from 'zod-validation-error';
import { AUXILIARY_FIELDS } from '@zenstackhq/sdk';
import { LoggerConfig } from './types';
import { LoggerConfig } from '../types';

export function getZodSchema(zodSchemas: ModelZodSchema, model: string, operation: keyof DbOperations) {
if (zodSchemas[model]) {
Expand Down Expand Up @@ -42,11 +42,19 @@ export function logError(logger: LoggerConfig | undefined | null, message: strin
}
}

export function logWarning(logger: LoggerConfig | undefined | null, message: string, code?: string) {
export function logWarning(logger: LoggerConfig | undefined | null, message: string) {
if (logger === undefined) {
console.warn(`@zenstackhq/server: error ${code ? '[' + code + ']' : ''}, ${message}`);
console.warn(`@zenstackhq/server: ${message}`);
} else if (logger?.warn) {
logger.warn(message, code);
logger.warn(message);
}
}

export function logInfo(logger: LoggerConfig | undefined | null, message: string) {
if (logger === undefined) {
console.log(`@zenstackhq/server: ${message}`);
} else if (logger?.info) {
logger.info(message);
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/server/src/express/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default as ZenStackMiddleware } from './middleware';
export * from './middleware';
Loading

0 comments on commit 53716c9

Please sign in to comment.