Skip to content
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

Docs: Knex + Objection Store #36

Open
coolaj86 opened this issue Aug 25, 2021 · 0 comments
Open

Docs: Knex + Objection Store #36

coolaj86 opened this issue Aug 25, 2021 · 0 comments

Comments

@coolaj86
Copy link
Contributor

coolaj86 commented Aug 25, 2021

Need to put this somewhere as an example.

db/migrations/<yyyy><mm><dd><hh><mm><ss>_kv.js:

'use strict';

exports.up = function (knex) {
  return knex.schema.createTable('kv', async function (table) {
    table.string('id').primary();
    table.json('json').notNullable();
  });
};

exports.down = function (knex) {
  return knex.schema.dropTableIfExists('kv');
};

src/models/kv.js:

'use strict';

let Objection = require('objection');

class KV extends Objection.Model {
  // Table name is the only required property.
  static tableName = 'kv';

  static get jsonAttributes() {
    return ['json'];
  }
}

module.exports = KV;

src/lib/store.js:

'use strict';

let VerificationCodeModel = require('./src/models/verification_code.js');

let Verifications = module.exports;

Verifications.get = async function (id) {
  let data = await VerificationCodeModel.query().findById(id);
  if (!data) {
    return null;
  }

  //@ts-ignore
  let result = data.json;
  /** type import('auth3000').Verification */
  return result;
};

/**
 * @param {string} id
 * @param {import('auth3000').Verification} value
 */
Verifications.set = async function (id, json) {
  //@ts-ignore
  let updated = await VerificationCodeModel.query().insert({ id, json }).onConflict().merge();
};

test.js:

#!/usr/bin/env node

'use strict';

require('dotenv').config();
require('./setup.js'); // load the ORM

let Store = require('./src/lib/kv.js');
let VCModel = require('./src/models/kv.js');

async function main() {
  let r0 = await Store.get('foo');
  if (r0) {
    console.log("Warn: previous test did not delete 'foo':", r0);
  }

  let rnd = Math.random().toString().replace('0.', '');
  await Store.set('foo', { banana: 'gram', [rnd]: true, rnd: rnd });

  let r2 = await Store.get('foo');
  if (!r2[rnd] || r2.rnd !== rnd) {
    throw new Error('did not save arbitrary JSON correctly');
  }

  let num = await VCModel.query().deleteById('foo');
  if (1 !== num) {
    if (num > 1) {
      throw new Error('deleted', num, 'values... oops');
    } else {
      throw new Error("didn't delete anything");
    }
  }
}

main()
  .then(function () {
    console.log('PASS');
    process.exit(0);
  })
  .catch(function (err) {
    console.error(err.stack);
    console.error('FAIL');
    process.exit(1);
  });

setup.js:

'use strict';

const Knex = require('knex');
const Objection = require('objection');

const knex = Knex({
  client: process.env.DB_CLIENT || 'pg',
  connection: process.env.DB_URL || 'postgres://postgres:postgres@localhost/postgres',
  pool: { min: 2, max: 99 },
  migrations: {
    directory: './db/migrations',
    tableName: 'knex_migrations',
  },
});

Objection.Model.knex(knex);
@coolaj86 coolaj86 changed the title Knex + Objection Store Docs: Knex + Objection Store Aug 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant