Skip to content

Instantly share code, notes, and snippets.

@newhouse
Created Apr 28, 2017
Embed
What would you like to do?
Objection.js $formatDatabaseJson bug hunt
'use strict';
const _ = require('lodash');
const objection = require('objection');
const Model = objection.Model;
const knex = require('knex')({
debug: false,
client: 'pg',
connection: 'INSERT CONNECTION STRING HERE',
pool: {
min: 2,
max: 2
}
});
Model.knex(knex);
const createTables = knex.schema.createTableIfNotExists('performance_test', table => {
table.string('object_id', 4).notNullable();
table.integer('frequency').notNullable();
table.timestamp('time').defaultTo(knex.fn.now());
table.primary(['object_id', 'frequency', 'time']);
});
const dropTables = knex.schema.dropTableIfExists('performance_test');
const FREQ_LONG_TO_SHORT = {
'minutely': 1,
'hourly': 2,
'daily': 3
};
const FREQ_SHORT_TO_LONG = _.invert(FREQ_LONG_TO_SHORT);
class Performance extends Model {
static get tableName() {
return 'performance_test';
}
static get idColumn() {
return ['object_id', 'time', 'frequency'];
}
static get jsonSchema() {
return {
type: 'object',
required: ['object_id', 'frequency', 'time'],
properties: {
object_id: {
type: 'string',
maxLength: 4
},
frequency: {
type: 'string',
enum: _.keys(FREQ_LONG_TO_SHORT)
},
time: {
type: 'string',
format: 'date-time'
}
}
};
}
// CALLED TO SERIALIZE OBJECT ON ITS WAY TO THE DATABASE
$formatDatabaseJson(json) {
json = super.$formatDatabaseJson(json);
// CONVERT LONG FREQ NAME TO SHORT FREQ NAME
if('frequency' in json) {
json.frequency = FREQ_LONG_TO_SHORT[json.frequency];
}
return json;
}
// CALLED WHEN OBJECT IS READ FROM THE DB FOR USE IN MODEL
$parseDatabaseJson(json) {
// CONVERT SHORT FREQ NAME TO LONG FREQ NAME
json.frequency = FREQ_SHORT_TO_LONG[json.frequency];
return super.$parseDatabaseJson(json);
}
}
// GO FOR IT
dropTables
.then(() => {
return createTables;
})
.then(() => {
console.log('CREATING INSTANCE');
return Performance
.query()
// .debug()
.insert({
object_id: '1234',
time: new Date().toISOString(),
frequency: 'daily'
})
.first()
.returning('*');
})
.then(instance => {
console.log('INSTANCE CREATED');
console.log(instance);
console.log('DELETING INSTANCE???');
return instance
.$query()
.debug()
.delete();
})
.then(() => {
console.log('YOU ARE THE GREATEST OF ALL TIME!');
return dropTables;
})
.catch(err => {
console.warn(err);
return dropTables
})
.then(() => {
process.exit();
})
.catch(() => {
process.exit();
});
{
"name": "objection-formatDatabaseJson",
"version": "0.0.1",
"description": "Objection 4-eva",
"main": "main.js",
"scripts": {
"start": "node ./app.js"
},
"engines": {
"node": "6.6.0"
},
"dependencies": {
"knex": "0.12.6",
"lodash": "latest",
"objection": "^0.6.2",
"pg": "^6.1.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment