Review this generated object-building code before it handles request payloads.
Build a public session from own userId and preferences.theme fields, default the role to viewer, keep nested data independent, and give each Session its own tags.
JavaScript
function buildSession(payload) {
const session = {};
for (const key in payload) {
session[key] = payload[key];
}
if (!session.role) session.role = 'viewer';
Object.freeze(session);
return session;
}
function Session(data) {
Object.assign(this, data);
}
Session.prototype.tags = [];
Session.prototype.addTag = function addTag(tag) {
this.tags.push(tag);
};
const inherited = { role: 'admin' };
const payload = Object.create(inherited);
payload.userId = 'u-7';
payload.preferences = { theme: 'dark' };
const first = new Session(buildSession(payload));
const second = new Session(buildSession(payload));
first.addTag('new');
generated code is illustrative, not from any one model