@getanthill/datastore
Version:
Event-Sourced Datastore
123 lines (113 loc) • 3.16 kB
text/typescript
import _ from 'lodash';
import * as c from '../constants';
import reducerFactory from './reducer';
import defaultSchemaBuilder, { mergeWithArrays } from './schema';
import Generic, { ModelDefinition } from './Generic';
import type { ModelConfig, GenericType, Services } from '../typings';
function addDefaultIndexes(modelConfig: ModelConfig): ModelConfig {
return _.mergeWith(
{},
{
indexes: [
{
collection: modelConfig.name,
fields: { created_at: 1 },
opts: { name: 'created_at' },
},
{
collection: modelConfig.name,
fields: { updated_at: 1 },
opts: { name: 'updated_at' },
},
{
collection: `${modelConfig.name}_events`,
fields: { created_at: 1 },
opts: { name: 'created_at' },
},
{
collection: `${modelConfig.name}_snapshots`,
fields: { created_at: 1 },
opts: { name: 'created_at' },
},
{
collection: `${modelConfig.name}_snapshots`,
fields: { updated_at: 1 },
opts: { name: 'updated_at' },
},
],
},
modelConfig,
mergeWithArrays,
);
}
export function Factory(
modelConfig: ModelConfig,
services: Services,
): GenericType {
const DEFINITION: ModelDefinition = {
DATABASE: modelConfig.db ?? c.DEFAULT_DATABASE_NAME,
COLLECTION: modelConfig.name,
COLLECTION_OPTIONS: {},
VALIDATOR_SCHEMA: {},
VALIDATOR_OPTIONS: {
validationLevel: 'off',
},
INDEXES: [
[
{
[modelConfig.correlation_field]: 1,
},
{
unique: true,
background: true,
name: 'correlation_id_unicity',
},
],
[
{
created_at: 1,
},
{
background: true,
name: 'created_at',
},
],
[
{
updated_at: 1,
},
{
background: true,
name: 'updated_at',
},
],
],
};
const SCHEMA = defaultSchemaBuilder(services, modelConfig);
const reducer = reducerFactory(SCHEMA, {
throwOnInvalidEvent: services.config.features.events.throwOnInvalidEvent,
model: SCHEMA.model,
modelConfig: modelConfig,
fhe:
services.config.features.fhe.isEnabled === true &&
modelConfig.with_fully_homomorphic_encryption === true
? services.fhe
: undefined,
});
const updatedModelConfig = addDefaultIndexes(modelConfig);
return Generic(DEFINITION, reducer, {
CORRELATION_FIELD: modelConfig.correlation_field,
CURRENT_HASH_FIELD: modelConfig.current_hash_field,
PREVIOUS_HASH_FIELD: modelConfig.previous_hash_field,
NONCE_FIELD: modelConfig.nonce_field,
WITH_GLOBAL_VERSION: modelConfig.with_global_version,
WITH_BLOCKCHAIN_HASH: modelConfig.with_blockchain_hash,
BLOCKCHAIN_HASH_DIFFICULTY: modelConfig.blockchain_hash_difficulty,
BLOCKCHAIN_HASH_GENESIS: modelConfig.blockchain_hash_genesis,
//
SCHEMA,
ORIGINAL_SCHEMA: modelConfig.schema,
MODEL_CONFIG: updatedModelConfig,
services,
});
}