Skip to content

Add schemas #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions Enterprise/static/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ const logger = new Logger('output');

const action = (id, handler) => {
const element = document.getElementById(id);
if (element) element.onclick = handler;
if (!element) return;
element.onclick = () => {
handler().catch((error) => {
logger.log(error.message);
});
};
};

const db = new Database('EnterpriseApplication', 1, (db) => {
Expand All @@ -38,7 +43,6 @@ const userService = new UserService(userRepository);
action('add', async () => {
const name = prompt('Enter user name:');
const age = parseInt(prompt('Enter age:'), 10);
if (!name || !Number.isInteger(age)) return;
const user = await userService.createUser(name, age);
logger.log('Added:', user);
});
Expand All @@ -49,12 +53,8 @@ action('get', async () => {
});

action('update', async () => {
try {
const user = await userService.incrementAge(1);
logger.log('Updated:', user);
} catch (err) {
logger.log(err.message);
}
const user = await userService.incrementAge(1);
logger.log('Updated:', user);
});

action('delete', async () => {
Expand Down
25 changes: 16 additions & 9 deletions Pragmatic/static/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ class Logger {

const logger = new Logger('output');
const schemas = {
user: { keyPath: 'id', autoIncrement: true },
user: {
id: { type: 'int', primary: true },
name: { type: 'str', index: true },
age: { type: 'int' },
},
};
const db = await new Database('Example', { version: 1, schemas });

const actions = {
add: async () => {
const name = prompt('Enter user name:');
if (!name) return;
const age = parseInt(prompt('Enter age:'), 10);
if (!Number.isInteger(age)) return;
const user = { name, age };
await db.insert({ store: 'user', record: user });
logger.log('Added:', user);
Expand Down Expand Up @@ -67,11 +69,16 @@ const actions = {
},
};

const init = () => {
for (const [id, handler] of Object.entries(actions)) {
const element = document.getElementById(id);
if (element) element.onclick = handler;
}
const action = (id, handler) => {
const element = document.getElementById(id);
if (!element) return;
element.onclick = () => {
handler().catch((error) => {
logger.log(error.message);
});
};
};

init();
for (const [id, handler] of Object.entries(actions)) {
action(id, handler);
}
29 changes: 25 additions & 4 deletions Pragmatic/static/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ class Database {
#upgrade(db) {
for (const [name, schema] of Object.entries(this.#schemas)) {
if (!db.objectStoreNames.contains(name)) {
const store = db.createObjectStore(name, schema);
const indexes = schema.indexes ?? [];
for (const { name: idxName, keyPath, options } of indexes) {
store.createIndex(idxName, keyPath, options);
const options = { keyPath: 'id', autoIncrement: true };
const store = db.createObjectStore(name, options);
for (const [field, def] of Object.entries(schema)) {
if (name !== 'id' && def.index) {
store.createIndex(field, field, { unique: false });
}
}
}
}
Expand All @@ -59,11 +61,30 @@ class Database {
});
}

validate({ store, record }) {
const schema = this.#schemas[store];
if (!schema) throw new Error(`Schema for ${store} is not defined`);
for (const [key, val] of Object.entries(record)) {
const field = schema[key];
const name = `Field ${store}.${key}`;
if (!field) throw new Error(`${name} is not defined`);
if (field.type === 'int') {
if (Number.isInteger(val)) continue;
throw new Error(`${name} expected to be integer`);
} else if (field.type === 'str') {
if (typeof val === 'string') continue;
throw new Error(`${name} expected to be string`);
}
}
}

insert({ store, record }) {
this.validate({ store, record });
return this.#exec(store, (objectStore) => objectStore.add(record));
}

update({ store, record }) {
this.validate({ store, record });
return this.#exec(store, (objectStore) => objectStore.put(record));
}

Expand Down
22 changes: 10 additions & 12 deletions Pragmatic/test/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import assert from 'node:assert/strict';
import 'fake-indexeddb/auto';
import { Database } from '../static/storage.js';

const schemas = {
user: {
id: { type: 'int', primary: true },
name: { type: 'str', index: true },
age: { type: 'int' },
},
};

test('Pragmatic: Database CRUD + DSL', async () => {
const db = await new Database('PragmaticDB', {
version: 1,
schemas: {
user: { keyPath: 'id', autoIncrement: true },
},
});
const db = await new Database('PragmaticDB', { version: 1, schemas });

// Insert
await db.insert({ store: 'user', record: { name: 'Marcus', age: 20 } });
Expand Down Expand Up @@ -74,12 +77,7 @@ test('Pragmatic: Database CRUD + DSL', async () => {
});

test('Pragmatic: Complex DSL', async () => {
const db = await new Database('ComplexDB', {
version: 1,
schemas: {
user: { keyPath: 'id', autoIncrement: true },
},
});
const db = await new Database('ComplexDB', { version: 1, schemas });

await db.insert({ store: 'user', record: { name: 'Marcus', age: 20 } });
await db.insert({ store: 'user', record: { name: 'Lucius', age: 20 } });
Expand Down