@dossierhq/core
Version:
The core Dossier library used by clients and server alike, used to interact with schema and entities directly, as well as remotely through a client.
75 lines • 2.68 kB
JavaScript
/// <reference types="./Schema.d.ts" />
import { ok } from '../ErrorResult.js';
import { BaseSchema } from './BaseSchema.js';
import { PublishedSchema } from './PublishedSchema.js';
import { schemaToPublished } from './schemaToPublished.js';
import { schemaUpdate } from './schemaUpdate.js';
import { schemaValidate } from './schemaValidate.js';
export class Schema extends BaseSchema {
cachedPublishedSchema = null;
static createAndValidate(update) {
const result = SchemaWithMigrations.createAndValidate(update);
if (!result.isOk())
return result;
const { migrations, ...specWithoutMigrations } = result.value.spec;
return ok(new Schema(specWithoutMigrations));
}
constructor(spec) {
super(spec);
}
validate() {
return schemaValidate(this);
}
toPublishedSchema() {
if (this.cachedPublishedSchema) {
return this.cachedPublishedSchema;
}
const publishedSpec = schemaToPublished(this);
this.cachedPublishedSchema = new PublishedSchema(publishedSpec);
return this.cachedPublishedSchema;
}
}
export class SchemaWithMigrations extends Schema {
static createAndValidate(update) {
const emptySpec = {
schemaKind: 'full',
version: 0,
entityTypes: [],
componentTypes: [],
patterns: [],
indexes: [],
migrations: [],
};
const empty = new SchemaWithMigrations(emptySpec);
return empty.updateAndValidate(update);
}
updateAndValidate(update) {
// Update
const updatedResult = schemaUpdate(this.spec, update);
if (updatedResult.isError())
return updatedResult;
const updatedSpec = updatedResult.value;
if (updatedSpec === this.spec) {
return ok(this); // no change
}
// Validate
const updatedSchema = new SchemaWithMigrations(updatedSpec);
const validateResult = updatedSchema.validate();
if (validateResult.isError())
return validateResult;
return ok(updatedSchema);
}
collectMigrationActionsSinceVersion(oldSchemaVersion) {
const migrationsToConsider = this.spec.migrations.filter((it) => it.version > oldSchemaVersion);
if (migrationsToConsider.length === 0) {
return [];
}
migrationsToConsider.sort((a, b) => a.version - b.version);
const actions = [];
for (const migration of migrationsToConsider) {
actions.push(...migration.actions);
}
return actions;
}
}
//# sourceMappingURL=Schema.js.map