Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '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();
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement