Skip to content

Commit 4f16ed2

Browse files
authored
Support writeOnly + required combination #149 (#756)
1 parent b3d7483 commit 4f16ed2

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

Diff for: src/middlewares/parsers/schema.preprocessor.ts

+22
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ export class SchemaPreprocessor {
287287
// This null check should no longer be necessary
288288
this.handleSerDes(pschema, nschema, options);
289289
this.handleReadonly(pschema, nschema, options);
290+
this.handleWriteonly(pschema, nschema, options);
290291
this.processDiscriminator(pschema, nschema, options);
291292
this.removeExamples(pschema, nschema, options)
292293
}
@@ -479,6 +480,27 @@ export class SchemaPreprocessor {
479480
}
480481
}
481482

483+
private handleWriteonly(
484+
parent: OpenAPIV3.SchemaObject,
485+
schema: OpenAPIV3.SchemaObject,
486+
opts,
487+
) {
488+
if (opts.kind === 'req') return;
489+
490+
const required = parent?.required ?? [];
491+
const prop = opts?.path?.[opts?.path?.length - 1];
492+
const index = required.indexOf(prop);
493+
if (schema.writeOnly && index > -1) {
494+
// remove required if writeOnly
495+
parent.required = required
496+
.slice(0, index)
497+
.concat(required.slice(index + 1));
498+
if (parent.required.length === 0) {
499+
delete parent.required;
500+
}
501+
}
502+
}
503+
482504
/**
483505
* extract all requestBodies' schemas from an operation
484506
* @param op

Diff for: test/resources/write.only.yaml

+10
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ components:
9595
# TODO add nested test
9696
ProductNested:
9797
type: object
98+
required:
99+
- "password"
98100
properties:
99101
id:
100102
type: string
@@ -117,9 +119,14 @@ components:
117119
type: array
118120
items:
119121
$ref: '#/components/schemas/Review'
122+
password:
123+
type: string
124+
writeOnly: true
120125

121126
Review:
122127
type: object
128+
required:
129+
- "review_password"
123130
properties:
124131
id:
125132
type: integer
@@ -132,3 +139,6 @@ components:
132139
writeOnly: true
133140
rating:
134141
type: integer
142+
review_password:
143+
type: string
144+
writeOnly: true

Diff for: test/write.only.spec.ts

+3
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ describe(packageJson.name, () => {
8686
name: 'some name',
8787
role: 'admin',
8888
price: 10.99,
89+
password: 'password_value'
8990
})
9091
.expect(200));
9192

@@ -96,9 +97,11 @@ describe(packageJson.name, () => {
9697
.send({
9798
name: 'some name',
9899
price: 10.99,
100+
password: 'password_value',
99101
reviews: [
100102
{
101103
rating: 5,
104+
review_password: 'review_password_value'
102105
},
103106
],
104107
})

0 commit comments

Comments
 (0)