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

Support writeOnly + required combination #149 #756

Merged
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
22 changes: 22 additions & 0 deletions src/middlewares/parsers/schema.preprocessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ export class SchemaPreprocessor {
// This null check should no longer be necessary
this.handleSerDes(pschema, nschema, options);
this.handleReadonly(pschema, nschema, options);
this.handleWriteonly(pschema, nschema, options);
this.processDiscriminator(pschema, nschema, options);
}
}
Expand Down Expand Up @@ -430,6 +431,27 @@ export class SchemaPreprocessor {
}
}

private handleWriteonly(
parent: OpenAPIV3.SchemaObject,
schema: OpenAPIV3.SchemaObject,
opts,
) {
if (opts.kind === 'req') return;

const required = parent?.required ?? [];
const prop = opts?.path?.[opts?.path?.length - 1];
const index = required.indexOf(prop);
if (schema.writeOnly && index > -1) {
// remove required if writeOnly
parent.required = required
.slice(0, index)
.concat(required.slice(index + 1));
if (parent.required.length === 0) {
delete parent.required;
}
}
}

/**
* extract all requestBodies' schemas from an operation
* @param op
Expand Down
10 changes: 10 additions & 0 deletions test/resources/write.only.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ components:
# TODO add nested test
ProductNested:
type: object
required:
- "password"
properties:
id:
type: string
Expand All @@ -117,9 +119,14 @@ components:
type: array
items:
$ref: '#/components/schemas/Review'
password:
type: string
writeOnly: true

Review:
type: object
required:
- "review_password"
properties:
id:
type: integer
Expand All @@ -132,3 +139,6 @@ components:
writeOnly: true
rating:
type: integer
review_password:
type: string
writeOnly: true
3 changes: 3 additions & 0 deletions test/write.only.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ describe(packageJson.name, () => {
name: 'some name',
role: 'admin',
price: 10.99,
password: 'password_value'
})
.expect(200));

Expand All @@ -96,9 +97,11 @@ describe(packageJson.name, () => {
.send({
name: 'some name',
price: 10.99,
password: 'password_value',
reviews: [
{
rating: 5,
review_password: 'review_password_value'
},
],
})
Expand Down