Skip to content

Commit

Permalink
Support writeOnly + required combination #149 (#756)
Browse files Browse the repository at this point in the history
  • Loading branch information
pdhau authored Feb 10, 2024
1 parent b3d7483 commit 4f16ed2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/middlewares/parsers/schema.preprocessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,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);
this.removeExamples(pschema, nschema, options)
}
Expand Down Expand Up @@ -479,6 +480,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

0 comments on commit 4f16ed2

Please sign in to comment.