How to use objection - 10 common examples

To help you get started, we’ve selected a few objection examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github feathersjs-ecosystem / feathers-objection / test / company.js View on Github external
object: { type: 'string' }
            }
          },
          'first.founder': { type: ['string', 'null'] }
        }
      },
      jsonArray: { type: ['array', 'null'] },
      jsonbObject: { type: ['object', 'null'] },
      jsonbArray: { type: ['array', 'null'] }
    }
  }

  // This object defines the relations to other models.
  static relationMappings = {
    ceos: {
      relation: Model.BelongsToOneRelation,
      modelClass: path.join(__dirname, '/people'),
      join: {
        from: 'companies.ceo',
        to: 'people.id'
      }
    },
    employees: {
      relation: Model.HasManyRelation,
      modelClass: path.join(__dirname, '/employee'),
      join: {
        from: 'companies.id',
        to: 'employees.companyId'
      }
    },
    clients: {
      relation: Model.HasManyRelation,
github feathersjs-ecosystem / feathers-objection / test / company.js View on Github external
jsonbArray: { type: ['array', 'null'] }
    }
  }

  // This object defines the relations to other models.
  static relationMappings = {
    ceos: {
      relation: Model.BelongsToOneRelation,
      modelClass: path.join(__dirname, '/people'),
      join: {
        from: 'companies.ceo',
        to: 'people.id'
      }
    },
    employees: {
      relation: Model.HasManyRelation,
      modelClass: path.join(__dirname, '/employee'),
      join: {
        from: 'companies.id',
        to: 'employees.companyId'
      }
    },
    clients: {
      relation: Model.HasManyRelation,
      modelClass: path.join(__dirname, '/client'),
      join: {
        from: 'companies.id',
        to: 'clients.companyId'
      }
    }
  }
}
github SelfKeyFoundation / Identity-Wallet / src / main / identity / id-attribute.js View on Github external
static async delete(id) {
		const tx = await transaction.start(this.knex());
		try {
			let attr = await this.query(tx)
				.findById(id)
				.eager('documents');
			// TODO: fix for multiple documents
			if (attr.documents) await Promise.all(attr.documents.map(d => d.$query(tx).delete()));
			await attr.$query(tx).delete();
			await tx.commit();
			return attr;
		} catch (error) {
			await tx.rollback();
			throw error;
		}
	}
github stelace / stelace / src / services / transaction.js View on Github external
if (rebuildTransactionInformation) {
      updateAttrs = await computeTransactionInformation(
        Object.assign(
          { transaction, platformId, env, req },
          _.omit(payload, ['metadata', 'platformData', 'status'])
        )
      )
    }

    const now = new Date().toISOString()

    if (status) {
      updateAttrs.status = status

      const newStatusHistoryStep = { status, date: now }
      updateAttrs.statusHistory = raw('?::jsonb || "statusHistory"', [ // prepend a jsonb array using PostgreSQL `||` operator
        JSON.stringify([newStatusHistoryStep])
      ])
    }

    if (metadata) {
      updateAttrs.metadata = Transaction.rawJsonbMerge('metadata', metadata)
    }
    if (platformData) {
      updateAttrs.platformData = Transaction.rawJsonbMerge('platformData', platformData)
    }

    const newTransaction = await Transaction.query().patchAndFetchById(transactionId, updateAttrs)

    // Synchronize internal availability when core transaction properties
    // (assetId, dates, quantity) or status are updated
    if (rebuildTransactionInformation || status) {
github FergusDevelopmentLLC / geodev-node-rest / server.js View on Github external
const express = require('express');
const Promise = require('bluebird');
const bodyParser = require('body-parser');
const path = require('path');
const helmet = require('helmet');
const logger = require('morgan');

const Model = require('objection').Model;
const Knex = require('knex');
const knexConfig = require('./knexfile');
const knex = Knex(knexConfig[process.env.NODE_ENV || 'development']);
Model.knex(knex);

// const mongoose = require('mongoose');
// mongoose.Promise = global.Promise;
// mongoose.connect('mongodb://localhost/geodevdb');

const app = express();

app.use(express.static(__dirname + "/public")); //allows serving of static files in public folder

// middleware
app.use(helmet());
app.use(logger('dev'));
github jc21 / nginx-proxy-manager / src / backend / models / access_list_auth.js View on Github external
// Objection Docs:
// http://vincit.github.io/objection.js/

const db    = require('../db');
const Model = require('objection').Model;

Model.knex(db);

class AccessListAuth extends Model {
    $beforeInsert () {
        this.created_on  = Model.raw('NOW()');
        this.modified_on = Model.raw('NOW()');

        // Default for meta
        if (typeof this.meta === 'undefined') {
            this.meta = {};
        }
    }

    $beforeUpdate () {
        this.modified_on = Model.raw('NOW()');
github damian-pastorini / reldens / packages / users / players-state-model.js View on Github external
static get relationMappings()
    {
        // to avoid require loop:
        const Players = require('./players-model');
        return {
            parent_player: {
                relation: Model.BelongsToOneRelation,
                modelClass: Players,
                join: {
                    from: 'players_state.player_id',
                    to: 'players.id'
                }
            }
        }
    }
github Vincit / objection.js / examples / koa-ts / models / Animal.ts View on Github external
static relationMappings = () => ({
    owner: {
      relation: Model.BelongsToOneRelation,
      // The related model.
      modelClass: Person,

      join: {
        from: 'animals.ownerId',
        to: 'persons.id'
      }
    }
  })
}
github Vincit / objection.js / examples / express / app.js View on Github external
var Knex = require('knex');
var morgan = require('morgan');
var express = require('express');
var bodyParser = require('body-parser');
var knexConfig = require('./knexfile');
var registerApi = require('./api');
var Model = require('objection').Model;

// Initialize knex.
var knex = Knex(knexConfig.development);

// Bind all Models to a knex instance. If you only have one database in
// your server this is all you have to do. For multi database systems, see
// the Model.bindKnex method.
Model.knex(knex);

var app = express()
  .use(bodyParser.json())
  .use(morgan('dev'))
  .set('json spaces', 2);

// Register our REST API.
registerApi(app);

// Error handling. The `ValidationError` instances thrown by objection.js have a `statusCode`
// property that is sent as the status code of the response.
app.use(function (err, req, res, next) {
  if (err) {
    res.status(err.statusCode || err.status || 500).send(err.data || err.message || {});
  } else {
    next();
github strues / boldr / packages / boldr-api / src / core / bootstrap.js View on Github external
static initDb() {
    logger.info('initDb: Binding to Knex instance and making a test query.');
    // bind Objection models to db instance.
    Model.knex(knex);
  }
}