Skip to content

Commit

Permalink
Merge pull request #7 from p10ns11y/fix/add-specifying-optional
Browse files Browse the repository at this point in the history
fix: Add specifying optional
  • Loading branch information
p10ns11y authored Nov 14, 2024
2 parents 45eaa56 + 6445691 commit 1e91573
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 34 deletions.
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ Imagine a hypothetical page component

## Make Required Schema Based on Configuration

You can make a Zod schema required based on a configuration (components need) using the makeSchemaRequired function.
You can make a Zod schema required based on a configuration (components need) using the transformSchema function.

```ts
import { z } from 'zod';
import { makeSchemaRequired } from 'adaptate';
import { transformSchema } from 'adaptate';

const schema = z.object({
name: z.string().optional(),
Expand All @@ -112,7 +112,7 @@ const config = {
},
};

const updatedSchema = makeSchemaRequired(schema, config);
const updatedSchema = transformSchema(schema, config);

updatedSchema.parse({
name: 'Davin',
Expand Down Expand Up @@ -194,7 +194,7 @@ I have attempted to recreate what I have done at work with the help of **ChatGPT
```diff
import { z, ZodObject, ZodArray, ZodTypeAny } from 'zod';

-export function makeSchemaRequired(schema: ZodTypeAny, config: any, parentData: any = {}) {
-export function transformSchema(schema: ZodTypeAny, config: any, parentData: any = {}) {
- const schemaWithConditionalRequirements = applyConditionalRequirements(schema, config, parentData);
-
- if (schemaWithConditionalRequirements instanceof ZodObject && typeof config === 'object' && !Array.isArray(config)) {
Expand All @@ -204,18 +204,18 @@ I have attempted to recreate what I have done at work with the help of **ChatGPT
- if (config[key] === true) {
- return [key, value.required()];
- } else if (typeof config[key] === 'object') {
- return [key, makeSchemaRequired(value, config[key], parentData)];
- return [key, transformSchema(value, config[key], parentData)];
- }
- return [key, value];
- })
- );
- return z.object(newShape).required();
- } else if (schemaWithConditionalRequirements instanceof ZodArray && config['*']) {
- const elementSchema = schemaWithConditionalRequirements.element;
- return z.array(makeSchemaRequired(elementSchema, config['*'], parentData));
- return z.array(transformSchema(elementSchema, config['*'], parentData));
- }
- return schemaWithConditionalRequirements;
+export function makeSchemaRequired(
+export function transformSchema(
+ schema: ZodTypeAny,
+ config: Config
+): ZodTypeAny {
Expand Down Expand Up @@ -274,7 +274,7 @@ I have attempted to recreate what I have done at work with the help of **ChatGPT
+
+ if (schema instanceof ZodArray && config['*']) {
+ // @ts-ignore
+ updatedSchema = makeSchemaRequired(schema.element, config['*']);
+ updatedSchema = transformSchema(schema.element, config['*']);
+ updatedSchema = z.array(schema.element.merge(updatedSchema));
+ } else if (schema instanceof ZodObject) {
+ // @ts-ignore
Expand Down
4 changes: 2 additions & 2 deletions coverage/coverage-summary.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{"total": {"lines":{"total":197,"covered":197,"skipped":0,"pct":100},"statements":{"total":197,"covered":197,"skipped":0,"pct":100},"functions":{"total":8,"covered":8,"skipped":0,"pct":100},"branches":{"total":82,"covered":75,"skipped":0,"pct":91.46},"branchesTrue":{"total":0,"covered":0,"skipped":0,"pct":100}}
,"/Users/peram/code/adaptate/packages/core/src/index.ts": {"lines":{"total":82,"covered":82,"skipped":0,"pct":100},"functions":{"total":3,"covered":3,"skipped":0,"pct":100},"statements":{"total":82,"covered":82,"skipped":0,"pct":100},"branches":{"total":36,"covered":36,"skipped":0,"pct":100}}
{"total": {"lines":{"total":199,"covered":199,"skipped":0,"pct":100},"statements":{"total":199,"covered":199,"skipped":0,"pct":100},"functions":{"total":8,"covered":8,"skipped":0,"pct":100},"branches":{"total":84,"covered":77,"skipped":0,"pct":91.66},"branchesTrue":{"total":0,"covered":0,"skipped":0,"pct":100}}
,"/Users/peram/code/adaptate/packages/core/src/index.ts": {"lines":{"total":84,"covered":84,"skipped":0,"pct":100},"functions":{"total":3,"covered":3,"skipped":0,"pct":100},"statements":{"total":84,"covered":84,"skipped":0,"pct":100},"branches":{"total":38,"covered":38,"skipped":0,"pct":100}}
,"/Users/peram/code/adaptate/packages/utils/src/load-yaml.ts": {"lines":{"total":14,"covered":14,"skipped":0,"pct":100},"functions":{"total":1,"covered":1,"skipped":0,"pct":100},"statements":{"total":14,"covered":14,"skipped":0,"pct":100},"branches":{"total":1,"covered":1,"skipped":0,"pct":100}}
,"/Users/peram/code/adaptate/packages/utils/src/openapi.ts": {"lines":{"total":101,"covered":101,"skipped":0,"pct":100},"functions":{"total":4,"covered":4,"skipped":0,"pct":100},"statements":{"total":101,"covered":101,"skipped":0,"pct":100},"branches":{"total":45,"covered":38,"skipped":0,"pct":84.44}}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "adaptate",
"version": "0.1.0-beta.2",
"version": "0.1.0-beta.3",
"author": {
"name": "Peramanathan Sathyamoorthy",
"url": "https://github.com/p10ns11y/adaptate.git"
Expand Down
6 changes: 3 additions & 3 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ Imagine a hypothetical page component

## Make Required Schema Based on Configuration

You can make a Zod schema required based on a configuration (components need) using the makeSchemaRequired function.
You can make a Zod schema required based on a configuration (components need) using the transformSchema function.

```ts
import { z } from 'zod';
import { makeSchemaRequired } from '@adaptate/core';
import { transformSchema } from '@adaptate/core';

const schema = z.object({
name: z.string().optional(),
Expand All @@ -95,7 +95,7 @@ const config = {
},
};

const updatedSchema = makeSchemaRequired(schema, config);
const updatedSchema = transformSchema(schema, config);

updatedSchema.parse({
name: 'Davin',
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adaptate/core",
"version": "0.1.0-beta.2",
"version": "0.1.0-beta.3",
"author": {
"name": "Peramanathan Sathyamoorthy",
"url": "https://github.com/p10ns11y/adaptate.git"
Expand Down
57 changes: 43 additions & 14 deletions packages/core/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import {
getDereferencedOpenAPIDocument,
openAPISchemaToZod,
} from '@adaptate/utils/openapi';
import { makeSchemaRequired, applyConditionalRequirements } from '../';
import { transformSchema, applyConditionalRequirements } from '../';

describe('makeSchemaRequired', () => {
describe('transformSchema', () => {
it('should make properties required based on the config', async () => {
let baseSchema = z.object({
category: z
Expand Down Expand Up @@ -46,7 +46,7 @@ describe('makeSchemaRequired', () => {
type: true,
};

let transformedSchema = makeSchemaRequired(baseSchema, config);
let transformedSchema = transformSchema(baseSchema, config);

let validData = {
category: {
Expand All @@ -61,7 +61,19 @@ describe('makeSchemaRequired', () => {
type: 'electronics',
};

let invalidDataMissingName = {
let invalidDataMissingCategoryName = {
category: {
subcategories: [
{
name: 'Phones',
items: ['iPhone', 'Samsung Galaxy', 'Google Pixel'],
},
],
},
type: 'electronics',
};

let invalidDataMissingSubCategoryName = {
category: {
subcategories: [{ items: ['iPhone', 'Samsung Galaxy'] }],
},
Expand All @@ -83,9 +95,11 @@ describe('makeSchemaRequired', () => {

expect(() => transformedSchema.parse(validData)).not.toThrow();

expect(() => baseSchema.parse(invalidDataMissingName)).not.toThrow();
expect(() =>
baseSchema.parse(invalidDataMissingSubCategoryName)
).not.toThrow();

expect(() => transformedSchema.parse(invalidDataMissingName))
expect(() => transformedSchema.parse(invalidDataMissingSubCategoryName))
.toThrowErrorMatchingInlineSnapshot(`
[ZodError: [
{
Expand Down Expand Up @@ -115,7 +129,7 @@ describe('makeSchemaRequired', () => {

// Re transforming the schema with different config
// Here making warrantyPeriod required
let reTransformedSchema = makeSchemaRequired(transformedSchema, {
let reTransformedSchema = transformSchema(transformedSchema, {
warrantyPeriod: true,
});

Expand All @@ -134,6 +148,19 @@ describe('makeSchemaRequired', () => {
]]
`);

let reReTransformedSchema = transformSchema(reTransformedSchema, {
category: {
name: false,
},
});

expect(() =>
reReTransformedSchema.parse({
...invalidDataMissingCategoryName,
warrantyPeriod: '2 years',
})
).not.toThrow();

expect(() => baseSchema.parse({})).not.toThrow();
expect(() =>
baseSchema.parse({
Expand Down Expand Up @@ -210,7 +237,7 @@ describe('makeSchemaRequired', () => {
},
};

let anotherTransformedSchema = makeSchemaRequired(
let anotherTransformedSchema = transformSchema(
z.array(baseSchema),
anotherConfig
);
Expand All @@ -232,14 +259,16 @@ describe('makeSchemaRequired', () => {
dereferencedOpenAPIDocument['components']['schemas']['Category']
);

let yetAnotherTransformedSchema = makeSchemaRequired(dataZodSchema, config);
let yetAnotherTransformedSchema = transformSchema(dataZodSchema, config);

expect(() =>
yetAnotherTransformedSchema.parse(validData['category'])
).not.toThrow();

expect(() =>
yetAnotherTransformedSchema.parse(invalidDataMissingName['category'])
yetAnotherTransformedSchema.parse(
invalidDataMissingSubCategoryName['category']
)
).toThrow();

expect(() =>
Expand All @@ -261,7 +290,7 @@ describe('makeSchemaRequired', () => {
},
};

const transformedSchema = makeSchemaRequired(baseSchema, config);
const transformedSchema = transformSchema(baseSchema, config);

const validData = [{ name: 'John', age: 30 }];
const invalidData = [{ age: 30 }];
Expand Down Expand Up @@ -299,7 +328,7 @@ describe('makeSchemaRequired', () => {
},
};

const transformedSchema = makeSchemaRequired(baseSchema, config);
const transformedSchema = transformSchema(baseSchema, config);

const validData = {
category: {
Expand Down Expand Up @@ -330,7 +359,7 @@ describe('makeSchemaRequired', () => {
const config = {};

expect(() =>
makeSchemaRequired(invalidSchema, config)
transformSchema(invalidSchema, config)
).toThrowErrorMatchingInlineSnapshot(
`[Error: The given schema must be a Zod object.]`
);
Expand All @@ -344,7 +373,7 @@ describe('makeSchemaRequired', () => {
// @ts-ignore
const config = [];
// @ts-ignore
const transformedSchema = makeSchemaRequired(baseSchema, config);
const transformedSchema = transformSchema(baseSchema, config);

expect(transformedSchema).toBeInstanceOf(z.ZodObject);
// @ts-ignore
Expand Down
11 changes: 7 additions & 4 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export type Config = Record<string, any>;
* city: true
* }
* };
* const updatedSchema = makeSchemaRequired(schema, config);
* const updatedSchema = transformSchema(schema, config);
* const validData = {
* name: 'John Doe',
* address: { city: 'New York' },
Expand All @@ -42,10 +42,10 @@ export type Config = Record<string, any>;
* schema.parse(invalidDataMissingName); // Should fail due to missing 'name'
* schema.parse(invalidDataMissingCity); // Should fail due to missing 'address.city'
* @category Helper
* @module makeSchemaRequired
* @module transformSchema
* */
// @ts-ignore
export function makeSchemaRequired(
export function transformSchema(
schema: ZodTypeAny,
config: Config
): ZodTypeAny {
Expand Down Expand Up @@ -73,6 +73,9 @@ export function makeSchemaRequired(
if (partialConfig[key] === true) {
// @ts-ignore
return [key, unwrappedValue];
} else if (partialConfig[key] === false) {
// @ts-ignore
return [key, unwrappedValue.optional()];
} else if (typeof partialConfig[key] === 'object') {
// @ts-ignore
return [key, extendSchema(value, partialConfig[key])];
Expand Down Expand Up @@ -104,7 +107,7 @@ export function makeSchemaRequired(

if (schema instanceof ZodArray && config['*']) {
// @ts-ignore
updatedSchema = makeSchemaRequired(schema.element, config['*']);
updatedSchema = transformSchema(schema.element, config['*']);
updatedSchema = z.array(schema.element.merge(updatedSchema));
} else if (schema instanceof ZodObject) {
// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adaptate/utils",
"version": "0.1.0-beta.2",
"version": "0.1.0-beta.3",
"author": {
"name": "Peramanathan Sathyamoorthy",
"url": "https://github.com/p10ns11y/adaptate.git"
Expand Down

0 comments on commit 1e91573

Please sign in to comment.