@mikro-orm/core
Version:
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
70 lines (69 loc) • 2.76 kB
JavaScript
import { Reference } from './Reference.js';
import { EntityAssigner } from './EntityAssigner.js';
import { EntitySerializer } from '../serialization/EntitySerializer.js';
import { helper } from './wrap.js';
/** Base class for entities providing convenience methods like `assign()`, `toObject()`, and `populate()`. */
export class BaseEntity {
/** Returns whether the entity has been fully loaded from the database. */
isInitialized() {
return helper(this).__initialized;
}
/** Marks the entity as populated or not for serialization purposes. */
populated(populated = true) {
helper(this).populated(populated);
}
/** Loads the specified relations on this entity. */
async populate(populate, options = {}) {
return helper(this).populate(populate, options);
}
/** Returns a Reference wrapper for this entity. */
toReference() {
return Reference.create(this);
}
toObject(ignoreFields) {
return helper(this).toObject(ignoreFields);
}
/** Converts the entity to a plain object, including all properties regardless of serialization rules. */
toPOJO() {
return helper(this).toPOJO();
}
/** Serializes the entity with control over which relations and fields to include or exclude. */
serialize(options) {
return EntitySerializer.serialize(this, options);
}
/** Assigns the given data to this entity, updating its properties and relations. */
assign(data, options = {}) {
return EntityAssigner.assign(this, data, options);
}
/** Initializes (refreshes) the entity by reloading it from the database. Returns null if not found. */
init(options) {
return helper(this).init(options);
}
/** Returns the database schema this entity belongs to. */
getSchema() {
return helper(this).getSchema();
}
/** Sets the database schema for this entity. */
setSchema(schema) {
helper(this).setSchema(schema);
}
}
Object.defineProperty(BaseEntity.prototype, '__baseEntity', { value: true, writable: false, enumerable: false });
/** Empty base for {@link Loadable} when called without arguments — standalone mixin, no inherited base. */
class EmptyBase {
}
export function Loadable(Base = EmptyBase) {
class LoadableMixin extends Base {
async load(options) {
return Reference.create(this).load(options);
}
async loadOrFail(options) {
return Reference.create(this).loadOrFail(options);
}
}
return LoadableMixin;
}
const LoadableBaseEntityBase = Loadable(BaseEntity);
/** Convenience: `BaseEntity` pre-composed with the `Loadable` mixin. */
export class LoadableBaseEntity extends LoadableBaseEntityBase {
}