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

Hidden properties when strict is false #5468

Merged
merged 1 commit into from
May 18, 2020
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
14 changes: 13 additions & 1 deletion packages/repository/src/__tests__/unit/model/model.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ describe('model', () => {
const flexibleDef = new ModelDefinition('Flexible');
flexibleDef
.addProperty('id', {type: 'string', id: true})
.addProperty('createdAt', Date)
.addSetting('hiddenProperties', ['createdAt'])
.addSetting('strict', false);

const addressDef = new ModelDefinition('Address');
Expand Down Expand Up @@ -121,8 +123,8 @@ describe('model', () => {

class Flexible extends Entity {
static definition = flexibleDef;

id: string;
createdAt?: Date;

constructor(data?: Partial<Flexible>) {
super(data);
Expand Down Expand Up @@ -460,6 +462,16 @@ describe('model', () => {
});
});

it('excludes hidden properties from toJSON() output with strict false', () => {
const flexible = new Flexible({
id: '123a',
createdAt: new Date(),
});
expect(flexible.toJSON()).to.eql({
id: '123a',
});
});

describe('rejectNavigationalPropertiesInData', () => {
class Order extends Entity {
static definition = new ModelDefinition('Order')
Expand Down
9 changes: 6 additions & 3 deletions packages/repository/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,17 +265,20 @@ export abstract class Model {
* See function `asObject` for each property's conversion rules.
*/
toObject(options?: Options): Object {
const def = (this.constructor as typeof Model).definition;
const obj: AnyObject = {};

if (options && options.ignoreUnknownProperties === false) {
const hiddenProperties: string[] = def?.settings.hiddenProperties || [];
for (const p in this) {
const val = (this as AnyObject)[p];
obj[p] = asObject(val, options);
if (!hiddenProperties.includes(p)) {
const val = (this as AnyObject)[p];
obj[p] = asObject(val, options);
}
}
return obj;
}

const def = (this.constructor as typeof Model).definition;
const props = def.properties;
const keys = Object.keys(props);

Expand Down