Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 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
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": "2.10.2",
"version": "2.11.0",
"description": "",
"scripts": {
"build": "pnpm -r --filter=\"!./packages/ide/*\" build",
Expand Down
2 changes: 1 addition & 1 deletion packages/ide/jetbrains/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ plugins {
}

group = "dev.zenstack"
version = "2.10.2"
version = "2.11.0"

repositories {
mavenCentral()
Expand Down
2 changes: 1 addition & 1 deletion packages/ide/jetbrains/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jetbrains",
"version": "2.10.2",
"version": "2.11.0",
"displayName": "ZenStack JetBrains IDE Plugin",
"description": "ZenStack JetBrains IDE plugin",
"homepage": "https://zenstack.dev",
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": "2.10.2",
"version": "2.11.0",
"displayName": "ZenStack modeling language compiler",
"description": "ZenStack modeling language compiler",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/misc/redwood/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/redwood",
"displayName": "ZenStack RedwoodJS Integration",
"version": "2.10.2",
"version": "2.11.0",
"description": "CLI and runtime for integrating ZenStack with RedwoodJS projects.",
"repository": {
"type": "git",
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": "2.10.2",
"version": "2.11.0",
"description": "ZenStack plugin and runtime supporting OpenAPI",
"main": "index.js",
"repository": {
Expand Down
12 changes: 10 additions & 2 deletions packages/plugins/openapi/src/rest-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -906,16 +906,24 @@ export class RESTfulOpenAPIGenerator extends OpenAPIGeneratorBase {
},
};

let idFieldSchema: OAPI.SchemaObject = { type: 'string' };
if (idFields.length === 1) {
// FIXME: JSON:API actually requires id field to be a string,
// but currently the RESTAPIHandler returns the original data
// type as declared in the ZModel schema.
idFieldSchema = this.fieldTypeToOpenAPISchema(idFields[0].type);
}

if (mode === 'create') {
// 'id' is required if there's no default value
const idFields = model.fields.filter((f) => isIdField(f));
if (idFields.length === 1 && !hasAttribute(idFields[0], '@default')) {
properties = { id: { type: 'string' }, ...properties };
properties = { id: idFieldSchema, ...properties };
toplevelRequired.unshift('id');
}
} else {
// 'id' always required for read and update
properties = { id: { type: 'string' }, ...properties };
properties = { id: idFieldSchema, ...properties };
toplevelRequired.unshift('id');
}

Expand Down
26 changes: 24 additions & 2 deletions packages/plugins/openapi/tests/openapi-restful.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ model Bar {

const { name: output } = tmp.fileSync({ postfix: '.yaml' });

const options = buildOptions(model, modelFile, output, '3.1.0');
const options = buildOptions(model, modelFile, output, specVersion);
await generate(model, options, dmmf);

console.log(`OpenAPI specification generated for ${specVersion}: ${output}`);
Expand Down Expand Up @@ -324,7 +324,7 @@ model Foo {

const { name: output } = tmp.fileSync({ postfix: '.yaml' });

const options = buildOptions(model, modelFile, output, '3.1.0');
const options = buildOptions(model, modelFile, output, specVersion);
await generate(model, options, dmmf);

console.log(`OpenAPI specification generated for ${specVersion}: ${output}`);
Expand All @@ -340,6 +340,28 @@ model Foo {
}
});

it('int field as id', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}

model Foo {
id Int @id @default(autoincrement())
}
`);

const { name: output } = tmp.fileSync({ postfix: '.yaml' });

const options = buildOptions(model, modelFile, output, '3.0.0');
await generate(model, options, dmmf);
console.log(`OpenAPI specification generated: ${output}`);
await OpenAPIParser.validate(output);

const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.components.schemas.Foo.properties.id.type).toBe('integer');
});

it('exposes individual fields from a compound id as attributes', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/swr",
"displayName": "ZenStack plugin for generating SWR hooks",
"version": "2.10.2",
"version": "2.11.0",
"description": "ZenStack plugin for generating SWR hooks",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/tanstack-query",
"displayName": "ZenStack plugin for generating tanstack-query hooks",
"version": "2.10.2",
"version": "2.11.0",
"description": "ZenStack plugin for generating tanstack-query hooks",
"main": "index.js",
"exports": {
Expand Down
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": "2.10.2",
"version": "2.11.0",
"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": "2.10.2",
"version": "2.11.0",
"description": "Runtime of ZenStack for both client-side and server-side environments.",
"repository": {
"type": "git",
Expand Down
12 changes: 12 additions & 0 deletions packages/runtime/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,15 @@ export const PRISMA_MINIMUM_VERSION = '5.0.0';
* Prefix for auxiliary relation field generated for delegated models
*/
export const DELEGATE_AUX_RELATION_PREFIX = 'delegate_aux';

/**
* Prisma actions that can have a write payload
*/
export const ACTIONS_WITH_WRITE_PAYLOAD = [
'create',
'createMany',
'createManyAndReturn',
'update',
'updateMany',
'upsert',
];
48 changes: 25 additions & 23 deletions packages/runtime/src/cross/nested-write-visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import type { FieldInfo, ModelMeta } from './model-meta';
import { resolveField } from './model-meta';
import { MaybePromise, PrismaWriteActionType, PrismaWriteActions } from './types';
import { getModelFields } from './utils';
import { enumerate, getModelFields } from './utils';

type NestingPathItem = { field?: FieldInfo; model: string; where: any; unique: boolean };

Expand Down Expand Up @@ -310,31 +310,33 @@ export class NestedWriteVisitor {
payload: any,
nestingPath: NestingPathItem[]
) {
for (const field of getModelFields(payload)) {
const fieldInfo = resolveField(this.modelMeta, model, field);
if (!fieldInfo) {
continue;
}
for (const item of enumerate(payload)) {
for (const field of getModelFields(item)) {
const fieldInfo = resolveField(this.modelMeta, model, field);
if (!fieldInfo) {
continue;
}

if (fieldInfo.isDataModel) {
if (payload[field]) {
// recurse into nested payloads
for (const [subAction, subData] of Object.entries<any>(payload[field])) {
if (this.isPrismaWriteAction(subAction) && subData) {
await this.doVisit(fieldInfo.type, subAction, subData, payload[field], fieldInfo, [
...nestingPath,
]);
if (fieldInfo.isDataModel) {
if (item[field]) {
// recurse into nested payloads
for (const [subAction, subData] of Object.entries<any>(item[field])) {
if (this.isPrismaWriteAction(subAction) && subData) {
await this.doVisit(fieldInfo.type, subAction, subData, item[field], fieldInfo, [
...nestingPath,
]);
}
}
}
}
} else {
// visit plain field
if (this.callback.field) {
await this.callback.field(fieldInfo, action, payload[field], {
parent: payload,
nestingPath,
field: fieldInfo,
});
} else {
// visit plain field
if (this.callback.field) {
await this.callback.field(fieldInfo, action, item[field], {
parent: item,
nestingPath,
field: fieldInfo,
});
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/src/enhancements/edge/encryption.ts
15 changes: 13 additions & 2 deletions packages/runtime/src/enhancements/node/create-enhancement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
} from '../../types';
import { withDefaultAuth } from './default-auth';
import { withDelegate } from './delegate';
import { withEncrypted } from './encryption';
import { withJsonProcessor } from './json-processor';
import { Logger } from './logger';
import { withOmit } from './omit';
Expand All @@ -20,7 +21,7 @@ import type { PolicyDef } from './types';
/**
* All enhancement kinds
*/
const ALL_ENHANCEMENTS: EnhancementKind[] = ['password', 'omit', 'policy', 'validation', 'delegate'];
const ALL_ENHANCEMENTS: EnhancementKind[] = ['password', 'omit', 'policy', 'validation', 'delegate', 'encryption'];

/**
* Options for {@link createEnhancement}
Expand Down Expand Up @@ -100,6 +101,7 @@ export function createEnhancement<DbClient extends object>(
}

const hasPassword = allFields.some((field) => field.attributes?.some((attr) => attr.name === '@password'));
const hasEncrypted = allFields.some((field) => field.attributes?.some((attr) => attr.name === '@encrypted'));
const hasOmit = allFields.some((field) => field.attributes?.some((attr) => attr.name === '@omit'));
const hasDefaultAuth = allFields.some((field) => field.defaultValueProvider);
const hasTypeDefField = allFields.some((field) => field.isTypeDef);
Expand All @@ -120,13 +122,22 @@ export function createEnhancement<DbClient extends object>(
}
}

// password enhancement must be applied prior to policy because it changes then length of the field
// password and encrypted enhancement must be applied prior to policy because it changes then length of the field
// and can break validation rules like `@length`
if (hasPassword && kinds.includes('password')) {
// @password proxy
result = withPassword(result, options);
}

if (hasEncrypted && kinds.includes('encryption')) {
if (!options.encryption) {
throw new Error('Encryption options are required for @encrypted enhancement');
}

// @encrypted proxy
result = withEncrypted(result, options);
}

// 'policy' and 'validation' enhancements are both enabled by `withPolicy`
if (kinds.includes('policy') || kinds.includes('validation')) {
result = withPolicy(result, options, context);
Expand Down
11 changes: 2 additions & 9 deletions packages/runtime/src/enhancements/node/default-auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */

import { ACTIONS_WITH_WRITE_PAYLOAD } from '../../constants';
import {
FieldInfo,
NestedWriteVisitor,
Expand Down Expand Up @@ -50,15 +51,7 @@ class DefaultAuthHandler extends DefaultPrismaProxyHandler {

// base override
protected async preprocessArgs(action: PrismaProxyActions, args: any) {
const actionsOfInterest: PrismaProxyActions[] = [
'create',
'createMany',
'createManyAndReturn',
'update',
'updateMany',
'upsert',
];
if (actionsOfInterest.includes(action)) {
if (args && ACTIONS_WITH_WRITE_PAYLOAD.includes(action)) {
const newArgs = await this.preprocessWritePayload(this.model, action as PrismaWriteActionType, args);
return newArgs;
}
Expand Down
Loading
Loading