Ark7 model used for both backend and frontend
npm install @ark7/modelIn many projects, duplicating identical models can lead to numerous bugs. The
@ark7/model library addresses this challenge by offering a unified model
class layer that operates seamlessly across various environments, ensuring
consistent business logic and reducing redundancy.
Supported Platforms:
- Node.js (MongoDB)
- Browser
- ProtocolBuffer
---
- Installation
- Quick Start
- Defining a Model
- Model
- Model Metadata
- Model Definition
- Discrimination
- Mixin
- Field
- Required vs. Optional
- Readonly
- Default Values
- Model.modelize()
- .toObject() & .toJSON()
- Data Level
- Attachment
- Built-in Types
- Email
- UUID
---
Install the package using npm:
``shell`
npm install @ark7/model
Add transform plugin to tsconfig.json:
`
// tsconfig.json
{
...
"plugins": [{
"transform": "@ark7/model/transformer"
}],
}
`
Models are defined by decorating the class with A7Model or using A7Model.provide(ModelClass).
`Typescript
// models/users.ts
import { A7Model } from '@ark7/model';
@A7Model({})
export class Name {
readonly first: string;
last: string;
}
export enum Gender {
MALE = 'MALE',
FEMALE = 'FEMALE',
}
@A7Model({})
export class User {
email: string;
name?: Name;
gender?: Gender;
}
// Another way to register User model:
//
// A7Model.provide(User)
`
Once a model is defined, class metadata, field metadata, and model schema can be retrieved through A7Model.getMetadata(ModelClass). For example:
`Typescript
@A7Model({})
class Name {
first: string;
last: string;
}
A7Model.getMetadata(Name).should.be.deepEqual({
modelClass: Name.prototype.constructor,
superClass: null,
configs: {
schema: {
name: 'Name',
props: [
{
modifier: 'PUBLIC',
name: 'first',
optional: false,
readonly: false,
type: 'string',
},
{
modifier: 'PUBLIC',
name: 'last',
optional: false,
readonly: false,
type: 'string',
},
],
},
},
fields: {},
name: 'Name',
});
`
Model-level configuration can be injected using either @A7Model() or @Config():
`Typescript
@A7Model
class MCModel { }
interface ModelConfig {
foo: string;
}
(A7Model.getMetadata(MCModel).configs as ModelConfig).foo.should.be.equal(
'bar'
);
`
`Typescript
@A7Model({
discriminatorKey: 'kind',
})
class Event extends StrictModel {
kind?: string;
}
@A7Model({})
class MouseEvent extends Event {
foo: string;
}
const ins = EventModel.modelize({
kind: 'MouseEvent',
foo: 'bar',
} as any);
ins.should.be.instanceof(MouseEvent);
const ins2 = MouseEvent.modelize({
foo: 'bar',
});
ins2.should.be.instanceof(MouseEvent);
ins2.toObject().should.be.deepEqual({
kind: 'MouseEvent',
foo: 'bar',
});
`
A model can mix in other models.
`Typescript
@A7Model({})
class M1 {
foo: string;
}
@A7Model({})
class M2 {
bar: string;
}
@A7Model({})
@Mixin(M1)
@Mixin(M2)
class CombinedModel extends Model {}
interface CombinedModel extends M1, M2 {}
`
The required modifier can be declared at the field metadata or schema level:
`Typescript
class Name {
first: string; // schema level required
@Required() // field metadata level required
last: string; // schema level required
}
`
Sometimes, the two levels may have conflicting opinions:
`Typescript
class Name {
first?: string; // schema level optional
@Required(false) // field metadata level: optional
last: string; // schema level: required
}
`
It depends on the adapter to resolve these conflicts.
The readonly modifier can be declared at the field metadata or schema level:
`Typescript
class Name {
readonly first: string; // schema level readonly
@Readonly() // field metadata level readonly
last: string; // schema level non-readonly
}
`
It depends on the adapter to resolve these conflicts.
The default value can be set at the field metadata level:
`Typescript
class Name {
@Default('foo')
first: string;
@Default(() => 'bar')
last: string;
}
`
`Typescript
import { A7Model, StrictModel } from '@ark7/model';
@A7Model({})
class Name extends StrictModel {
first: string;
last: string;
}
@A7Model({})
export class User extends StrictModel {
email: string;
name?: Name;
}
const user = User.modelize({
email: 'test@google.com',
name: {
first: 'foo',
last: 'bar',
}
});
user.should.be.instanceof(User);
user.name.should.be.instanceof(Name);
`
`Typescript
import { A7Model, StrictModel } from '@ark7/model';
@A7Model({})
class Name extends StrictModel {
first: string;
last: string;
}
@A7Model({})
export class User extends StrictModel {
email: string;
name?: Name;
}
const user = User.modelize({
email: 'test@google.com',
name: {
first: 'foo',
last: 'bar',
}
});
user.toObject().should.be.instanceof({
email: 'test@google.com',
name: {
first: 'foo',
last: 'bar',
}
});
`
Each field is assigned a level number. The higher the level number, the more restricted or confidential the field is. We have predefined five data levels:
1. BASIC (10) - The basic field that will be used in the most scenarios.
Usually, presented when it's referenced by other model.
2. SHORT (20) - The fields that are useful for displaying as a list or
table. Usually, presented in the find or search endpoints.
3. DETAIL (30) - The fields that contains detail information. Usually,
presented in the get endpoints.
4. CONFIDENTIAL (40) - The fields that contains sensitive information.
Usually, not returning to the client or only to
admins with special privileges.
5. NEVER (1000) - The fields that are never returns.
Projection:
We can do the projection by providing a filter level. Any fields with level
numbers that are smaller or equal to the filter level will be projected. You can
tune the filter level by specifying the passLevelMap in the option.
`Typescript
@A7Model({})
class Name extends StrictModel {
@Basic() first: string;
@Basic() last: string;
}
@A7Model({})
export class User extends StrictModel {
@Basic() email: string;
@Short() name?: Name;
}
const user = User.modelize({
email: 'test@google.com',
name: {
first: 'foo',
last: 'bar',
}
});
user.toObject({ level: DefaultDataLevel.BASIC }).should.be.instanceof({
email: 'test@google.com',
});
user.toObject({ level: DefaultDataLevel.SHORT }).should.be.instanceof({
email: 'test@google.com',
name: {
first: 'foo',
last: 'bar',
},
});
`
Population:
For a reference field, when the filter level is greater than the
populateLevel specified by the option, the field will be populated.
`typescript
@A7Model({})
export class User extends Model {
@Virtual({ ... })
@Level({ populateLevel: DefaultDataLevel.DETAIL })
posts: Post[];
}
@A7Model({})
export class Post extends Model {
author: Ref
}
`
Sometimes, it's necessary to attach metadata to an instance.
`Typescript
import { A7Model, StrictModel } from '@ark7/model';
@A7Model({})
class Name extends StrictModel {
first: string;
last: string;
}
const name = Name.modelize({ first: 'foo', last: 'bar'});
name.$attach({ hello: 'world' });
name.$attach().should.be.deepEqual({
__$attach: true,
hello: 'world',
});
// This won't affect toObject() or toJSON():
name.toObject().should.be.deepEqual({
first: 'foo',
last: 'bar',
});
``
Email address.
StringUUID.