Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use zod parse result data as mutation input #997

Merged
merged 1 commit into from
Feb 13, 2024
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
26 changes: 21 additions & 5 deletions packages/runtime/src/enhancements/policy/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
// there's no nested write and we've passed input check, proceed with the create directly

// validate zod schema if any
this.validateCreateInputSchema(this.model, args.data);
args.data = this.validateCreateInputSchema(this.model, args.data);

// make a create args only containing data and ID selection
const createArgs: any = { data: args.data, select: this.utils.makeIdSelection(this.model) };
Expand Down Expand Up @@ -305,12 +305,20 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
// visit the create payload
const visitor = new NestedWriteVisitor(this.modelMeta, {
create: async (model, args, context) => {
this.validateCreateInputSchema(model, args);
const validateResult = this.validateCreateInputSchema(model, args);
if (validateResult !== args) {
this.utils.replace(args, validateResult);
}
pushIdFields(model, context);
},

createMany: async (model, args, context) => {
enumerate(args.data).forEach((item) => this.validateCreateInputSchema(model, item));
enumerate(args.data).forEach((item) => {
const r = this.validateCreateInputSchema(model, item);
if (r !== item) {
this.utils.replace(item, r);
}
});
pushIdFields(model, context);
},

Expand All @@ -319,7 +327,9 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
throw this.utils.validationError(`'where' field is required for connectOrCreate`);
}

this.validateCreateInputSchema(model, args.create);
if (args.create) {
args.create = this.validateCreateInputSchema(model, args.create);
}

const existing = await this.utils.checkExistence(db, model, args.where);
if (existing) {
Expand Down Expand Up @@ -468,6 +478,9 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
parseResult.error
);
}
return parseResult.data;
} else {
return data;
}
}

Expand Down Expand Up @@ -495,7 +508,10 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
} else if (inputCheck === true) {
this.validateCreateInputSchema(this.model, item);
const r = this.validateCreateInputSchema(this.model, item);
if (r !== item) {
this.utils.replace(item, r);
}
} else if (inputCheck === undefined) {
// static policy check is not possible, need to do post-create check
needPostCreateCheck = true;
Expand Down
21 changes: 21 additions & 0 deletions packages/runtime/src/enhancements/policy/policy-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1276,6 +1276,27 @@ export class PolicyUtil {
return value ? deepcopy(value) : {};
}

/**
* Replace content of `target` object with `withObject` in-place.
*/
replace(target: any, withObject: any) {
if (!target || typeof target !== 'object' || !withObject || typeof withObject !== 'object') {
return;
}

// remove missing keys
for (const key of Object.keys(target)) {
if (!(key in withObject)) {
delete target[key];
}
}

// overwrite keys
for (const [key, value] of Object.entries(withObject)) {
target[key] = value;
}
}

/**
* Picks properties from an object.
*/
Expand Down
6 changes: 5 additions & 1 deletion packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ async function generateModelSchema(model: DataModel, project: Project, output: s
////////////////////////////////////////////////

// schema for validating prisma create input (all fields optional)
let prismaCreateSchema = makePartial('baseSchema');
let prismaCreateSchema = makePassthrough(makePartial('baseSchema'));
if (refineFuncName) {
prismaCreateSchema = `${refineFuncName}(${prismaCreateSchema})`;
}
Expand Down Expand Up @@ -501,3 +501,7 @@ function makeOmit(schema: string, fields: string[]) {
function makeMerge(schema1: string, schema2: string): string {
return `${schema1}.merge(${schema2})`;
}

function makePassthrough(schema: string) {
return `${schema}.passthrough()`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ describe('With Policy: field validation', () => {
text3 String @length(min: 3)
text4 String @length(max: 5)
text5 String? @endsWith('xyz')
text6 String? @trim @lower
text7 String? @upper

@@allow('all', true)
}
Expand Down Expand Up @@ -495,4 +497,61 @@ describe('With Policy: field validation', () => {
})
).toResolveTruthy();
});

it('string transformation', async () => {
await db.user.create({
data: {
id: '1',
password: 'abc123!@#',
email: '[email protected]',
handle: 'user1',
},
});

await expect(
db.userData.create({
data: {
userId: '1',
a: 1,
b: 0,
c: -1,
d: 0,
text1: 'abc123',
text2: 'def',
text3: 'aaa',
text4: 'abcab',
text6: ' AbC ',
text7: 'abc',
},
})
).resolves.toMatchObject({ text6: 'abc', text7: 'ABC' });

await expect(
db.user.create({
data: {
id: '2',
password: 'abc123!@#',
email: '[email protected]',
handle: 'user2',
userData: {
create: {
a: 1,
b: 0,
c: -1,
d: 0,
text1: 'abc123',
text2: 'def',
text3: 'aaa',
text4: 'abcab',
text6: ' AbC ',
text7: 'abc',
},
},
},
include: { userData: true },
})
).resolves.toMatchObject({
userData: expect.objectContaining({ text6: 'abc', text7: 'ABC' }),
});
});
});
Loading