Skip to content

Commit

Permalink
Treat projection as a private case of 'kindMemory'
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel committed Sep 20, 2023
1 parent 13d967c commit 862b5d6
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions lib/kinds.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,25 @@ const SCOPE = ['application', 'global', 'local'];
const STORE = ['persistent', 'memory'];
const ALLOW = ['write', 'append', 'read'];

const KIND_STORED_DEFAULT_META = {
scope: 'application',
store: 'persistent',
allow: 'write',
};
const KIND_MEMORY_DEFAULT_META = {
scope: 'local',
store: 'memory',
allow: 'write',
};

const withDefaults = (meta, defaults, extra) => {
const result = { ...meta, ...extra };
for (const [key, defaultValue] of Object.entries(defaults)) {
if (result[key] === undefined) result[key] = defaultValue;
}
return result;
};

const projection = (kind, meta, root) => {
const { schema: schemaName, fields: fieldNames } = meta;
if (!schemaName) throw new Error('Invalid Projection: "schema" expected');
Expand All @@ -24,29 +43,30 @@ const projection = (kind, meta, root) => {
if (referencedFields) {
for (const name of fieldNames) defs[name] = referencedFields[name];
}
const { scope = 'local', store = 'memory', allow = 'write', ...rest } = meta;
const metadata = { kind, scope, store, allow, parent: schemaName, ...rest };
const metadata = withDefaults(meta, KIND_MEMORY_DEFAULT_META, {
kind,
parent: schemaName,
});
return { defs, metadata };
};

const kindStored = (kind, meta, root) => {
const { scope = 'application', store = 'persistent', allow = 'write' } = meta;
const metadata = { ...meta, kind, scope, store, allow };
if (!root) throw new Error('"root" schema expected');
const id = root.name ? `${toLowerCamel(root.name)}Id` : 'id';
const defs = { [id]: '?string' };
const metadata = withDefaults(meta, KIND_STORED_DEFAULT_META, { kind });
return { defs, metadata };
};

const kindMemory = (kind, meta) => {
const { scope = 'local', store = 'memory', allow = 'write' } = meta;
return { metadata: { ...meta, kind, scope, store, allow }, defs: {} };
const kindMemory = (kind, meta, root) => {
if (kind === 'projection') return projection(kind, meta, root);
const metadata = withDefaults(meta, KIND_MEMORY_DEFAULT_META, { kind });
return { defs: {}, metadata };
};

const getKindMetadata = (kind, meta = {}, root) => {
if (kind === 'projection') return projection(kind, meta, root);
if (KIND_MEMORY.includes(kind)) return kindMemory(kind, meta);
if (KIND_STORED.includes(kind)) return kindStored(kind, meta, root);
return kindMemory(kind, meta);
const processKind = KIND_STORED.includes(kind) ? kindStored : kindMemory;
return processKind(kind, meta, root);
};

module.exports = {
Expand Down

0 comments on commit 862b5d6

Please sign in to comment.