Skip to content

Instantly share code, notes, and snippets.

@prashaantt
Last active December 26, 2016 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prashaantt/8b1255fdf18a49e1bb4ce8398bad18b3 to your computer and use it in GitHub Desktop.
Save prashaantt/8b1255fdf18a49e1bb4ce8398bad18b3 to your computer and use it in GitHub Desktop.
Experiments with a tiny DB wrapper
// abstract: don't allow direct instantiation
abstract class BaseTable<T> {
// model holds the schema
protected model: T;
// convert kebab_case to camelCase
private camelCase(key: string) {
return key.replace(/_(\w)/g, function (...captures: string[]) {
return captures[1].toUpperCase();
});
}
// convert camelCase to kebab_case (naïve impl)
private kebabCase(key: string) {
let kebabKey = '';
for (let i = 0; i < key.length; i++) {
if (key[i] === key[i].toLowerCase()) {
kebabKey += key[i];
}
else {
kebabKey += '_' + key[i].toLowerCase();
}
}
return kebabKey;
}
constructor(model?: T) {
if (model) {
this.model = model;
}
}
// init table from a database object
initFromDb(model: any) {
if (this.model) {
throw new Error('Model already constructed via constructor!');
}
const newModel = {} as T;
for (let key in model) {
// convert snake_cased db field to camelCase
const camelKey = this.camelCase(key);
Object.assign(newModel, { [camelKey]: model[key] });
}
this.model = newModel;
}
// serialise to kebab_cased db object
toDbObject() {
const dbObj = {};
const model = this.model;
for (let key in model) {
const kebabKey = this.kebabCase(key);
Object.assign(dbObj, { [kebabKey]: model[key] });
}
return dbObj;
}
// serialise to camelCased JSON
toString() {
return JSON.stringify(this.model);
}
}
interface Model {
id: number;
postId: number;
parentName: string;
}
class Table extends BaseTable<Model> {
show() {
return this.model.postId + ': ' + this.model.parentName;
}
}
let table = new Table({
id: 99,
postId: 77,
parentName: 'the parent'
});
console.log(table.toDbObject());
console.log(table.toString());
console.log(table.show());
table = new Table();
table.initFromDb({
id: 99,
post_id: 77,
parent_name: 'the parent'
});
console.log(table.toDbObject());
console.log(table.toString());
console.log(table.show());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment