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
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {},
"scripts": {
"build": "pnpm -r build",
"test": "pnpm -r test"
},
"keywords": [],
"author": "",
"license": "ISC"
Expand Down
2 changes: 1 addition & 1 deletion packages/internal/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/internal",
"version": "0.1.6",
"version": "0.1.18",
"description": "ZenStack internal runtime library",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
39 changes: 8 additions & 31 deletions packages/internal/src/handler/data/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { QueryProcessor } from './query-processor';
const PRISMA_ERROR_MAPPING: Record<string, ServerErrorCode> = {
P2002: ServerErrorCode.UNIQUE_CONSTRAINT_VIOLATION,
P2003: ServerErrorCode.REFERENCE_CONSTRAINT_VIOLATION,
P2025: ServerErrorCode.REFERENCE_CONSTRAINT_VIOLATION,
};

export default class DataHandler<DbClient> implements RequestHandler {
Expand Down Expand Up @@ -125,9 +126,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
r = await db.findMany(processedArgs);
}

console.log(
`Finding ${model}:\n${JSON.stringify(processedArgs, undefined, 2)}`
);
console.log(`Finding ${model}:\n${JSON.stringify(processedArgs)}`);
await this.queryProcessor.postProcess(
model,
processedArgs,
Expand Down Expand Up @@ -163,13 +162,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
);

const r = await db.$transaction(async (tx: any) => {
console.log(
`Create ${model}:\n${JSON.stringify(
processedArgs,
undefined,
2
)}`
);
console.log(`Create ${model}:\n${JSON.stringify(processedArgs)}`);
const created = await tx[model].create(processedArgs);

let queryArgs = {
Expand All @@ -184,11 +177,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
context
);
console.log(
`Finding created ${model}:\n${JSON.stringify(
queryArgs,
undefined,
2
)}`
`Finding created ${model}:\n${JSON.stringify(queryArgs)}`
);
const found = await tx[model].findFirst(queryArgs);
if (!found) {
Expand Down Expand Up @@ -247,9 +236,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
updateArgs.where = { ...updateArgs.where, id };

const r = await db.$transaction(async (tx: any) => {
console.log(
`Update ${model}:\n${JSON.stringify(updateArgs, undefined, 2)}`
);
console.log(`Update ${model}:\n${JSON.stringify(updateArgs)}`);
const updated = await tx[model].update(updateArgs);

// make sure after update, the entity passes policy check
Expand All @@ -265,11 +252,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
context
);
console.log(
`Finding post-updated ${model}:\n${JSON.stringify(
queryArgs,
undefined,
2
)}`
`Finding post-updated ${model}:\n${JSON.stringify(queryArgs)}`
);
const found = await tx[model].findFirst(queryArgs);
if (!found) {
Expand Down Expand Up @@ -321,9 +304,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
);
delArgs.where = { ...delArgs.where, id };

console.log(
`Deleting ${model}:\n${JSON.stringify(delArgs, undefined, 2)}`
);
console.log(`Deleting ${model}:\n${JSON.stringify(delArgs)}`);
const db = (this.service.db as any)[model];
const r = await db.delete(delArgs);
await this.queryProcessor.postProcess(
Expand Down Expand Up @@ -353,11 +334,7 @@ export default class DataHandler<DbClient> implements RequestHandler {
context
);
console.log(
`Finding to-be-deleted ${model}:\n${JSON.stringify(
readArgs,
undefined,
2
)}`
`Finding to-be-deleted ${model}:\n${JSON.stringify(readArgs)}`
);
const read = await db.findFirst(readArgs);
if (!read) {
Expand Down
1 change: 1 addition & 0 deletions packages/internal/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './types';
export * from './request-handler';
export * as request from './request';
60 changes: 43 additions & 17 deletions packages/internal/src/request.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import useSWR, { useSWRConfig } from 'swr';
import type { ScopedMutator } from 'swr/dist/types';
import type { MutatorCallback, MutatorOptions } from 'swr/dist/types';

const fetcher = async (url: string, options?: RequestInit) => {
const res = await fetch(url, options);
Expand All @@ -15,17 +15,17 @@ const fetcher = async (url: string, options?: RequestInit) => {
};

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

export function get<Data, Error = any>(url: string, args?: unknown) {
return useSWR<Data, Error>(makeUrl(url, args), fetcher);
export function get<Data, Error = any>(url: string | null, args?: unknown) {
return useSWR<Data, Error>(url && makeUrl(url, args), fetcher);
}

export async function post<Data, Result>(
url: string,
data: Data,
mutate: ScopedMutator<any>
mutate: Mutator
) {
const r: Result = await fetcher(url, {
method: 'POST',
Expand All @@ -34,14 +34,14 @@ export async function post<Data, Result>(
},
body: JSON.stringify(data),
});
mutate(url);
mutate(url, true);
return r;
}

export async function put<Data, Result>(
url: string,
data: Data,
mutate: ScopedMutator<any>
mutate: Mutator
) {
const r: Result = await fetcher(url, {
method: 'PUT',
Expand All @@ -50,26 +50,52 @@ export async function put<Data, Result>(
},
body: JSON.stringify(data),
});
mutate(url, r);
mutate(url, true);
return r;
}

export async function del<Result>(
url: string,
args: unknown,
mutate: ScopedMutator<any>
) {
export async function del<Result>(url: string, args: unknown, mutate: Mutator) {
const reqUrl = makeUrl(url, args);
const r: Result = await fetcher(reqUrl, {
method: 'DELETE',
});
const path = url.split('/');
path.pop();
mutate(path.join('/'));
mutate(path.join('/'), true);
return r;
}

export function getMutate() {
const { mutate } = useSWRConfig();
return mutate;
type Mutator = (
key: string,
prefix: boolean,
data?: any | Promise<any> | MutatorCallback,
opts?: boolean | MutatorOptions
) => Promise<any[]>;

export function getMutate(): Mutator {
// https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
const { cache, mutate } = useSWRConfig();
return (
key: string,
prefix: boolean,
data?: any | Promise<any> | MutatorCallback,
opts?: boolean | MutatorOptions
) => {
if (!prefix) {
return mutate(key, data, opts);
}

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' && k.startsWith(key)
) as string[];
console.log('Mutating keys:', JSON.stringify(keys));
const mutations = keys.map((key) => mutate(key, data, opts));
return Promise.all(mutations);
};
}
75 changes: 0 additions & 75 deletions packages/internal/src/request/index.ts

This file was deleted.

9 changes: 9 additions & 0 deletions packages/runtime/hooks.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
import { ServerErrorCode } from '@zenstackhq/internal';

export * from '.zenstack/lib/hooks';
export type HooksError = {
status: number;
info: {
code: ServerErrorCode;
message: string;
};
};
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/runtime",
"version": "0.1.17",
"version": "0.1.18",
"description": "ZenStack generated runtime code",
"main": "index.js",
"types": "index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "zenstack",
"displayName": "ZenStack CLI and Language Tools",
"description": "ZenStack CLI and Language Tools",
"version": "0.1.22",
"version": "0.1.32",
"engines": {
"vscode": "^1.56.0"
},
Expand Down
19 changes: 15 additions & 4 deletions packages/schema/src/generator/next-auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Context, Generator } from '../types';
import { Project } from 'ts-morph';
import * as path from 'path';
import colors from 'colors';

export default class NextAuthGenerator implements Generator {
async generate(context: Context) {
Expand All @@ -11,6 +12,8 @@ export default class NextAuthGenerator implements Generator {
this.generateAuthorize(project, context);

await project.save();

console.log(colors.blue(` ✔️ Next-auth adapter generated`));
}

generateIndex(project: Project, context: Context) {
Expand Down Expand Up @@ -118,6 +121,10 @@ export default class NextAuthGenerator implements Generator {
return async (
credentials: Record<'email' | 'password', string> | undefined
) => {
if (!credentials) {
throw new Error('Missing credentials');
}

try {
let maybeUser = await service.db.user.findFirst({
where: {
Expand All @@ -132,14 +139,14 @@ export default class NextAuthGenerator implements Generator {
});

if (!maybeUser) {
if (!credentials!.password || !credentials!.email) {
if (!credentials.password || !credentials.email) {
throw new Error('Invalid Credentials');
}

maybeUser = await service.db.user.create({
data: {
email: credentials!.email,
password: await hashPassword(credentials!.password),
email: credentials.email,
password: await hashPassword(credentials.password),
},
select: {
id: true,
Expand All @@ -149,8 +156,12 @@ export default class NextAuthGenerator implements Generator {
},
});
} else {
if (!maybeUser.password) {
throw new Error('Invalid User Record');
}

const isValid = await verifyPassword(
credentials!.password,
credentials.password,
maybeUser.password
);

Expand Down
Loading