How to use the objection.transaction function in objection

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 strues / boldr / src / api / routes / auth / providers / google.js View on Github external
account.save((err) => {
          res.send('Facebook account has been linked.');
          done(err, account);
        });
      }
    } else {
      const existingAccount = await Account.query().where({ google_id: profile._json.id }).first();
      if (existingAccount) {
        return done(null, existingAccount);
      }
      const existingEmailAccount = Account.query().where({ email: profile._json.email }).first();
      if (existingEmailAccount) {
        done();
      }

      const newAccount = await objection.transaction(Account, async (Account) => {
        const account = await Account
            .query()
            .insert({
              id: uuid.v4(),
              email: profile.emails[0].value,
            });
        await account.$relatedQuery('role').relate({ id: 1 });

        if (!account) {
          res.status(500).json('Oooops');
        }
        // here we create the profile
        // only inserting the uuid because creating the account doesnt require any of the data
        // you would find in the profile.
        const profile = await account.$relatedQuery('profile').insert({
          id: uuid.v4(),
github contentjet / contentjet-api / src / viewsets / EntryViewSet.ts View on Github external
const entryType = await EntryType.getById(entryTypeId);
    const { project, user } = ctx.state;
    if (!entryType || entryType.projectId !== project.id) {
      throw new ValidationError('Entry type with the provided id does not exist in project');
    }
    // Check the entry fields are valid against the entry type's fields
    await this.validateFields(entryType, fields, project.id);
    // Prepare the data for insertion into database
    const entryData = cloneDeep(ctx.request.body);
    delete entryData.tags;
    delete entryData.modifiedAt;
    entryData.userId = user.id;
    entryData.modifiedByUserId = user.id;
    entryData.fields = Entry.externalFieldsToInternal(entryType.fields, fields);
    const knex = Entry.knex();
    return await transaction(knex, async trx => {
      // Create new entry
      const entry = await Entry.create(entryData, trx);
      if (!entry) throw new DatabaseError();
      // Get or create tags and relate them to entry
      let entryTags = await EntryTag.bulkGetOrCreate(tags, project.id, trx);
      entryTags = await entry.setTags(entryTags, trx);
      const entryJSON = entry.toJSON() as any;
      entryJSON.tags = entryTags.map(entryTag => entryTag.name);
      entryJSON.fields = await entry.internalFieldsToExternal(entryType.fields, trx);
      ctx.body = entryJSON;
      ctx.state.viewsetResult = {
        action: 'create',
        modelClass: Entry,
        data: entryJSON
      };
      return entry;
github Vincit / objection.js / examples / express / api.js View on Github external
app.post('/persons/:id/movies', function (req, res, next) {
    // Inserting a movie for a person creates two queries: the movie insert query
    // and the join table row insert query. It is wise to use a transaction here.
    objection.transaction(Person.knex(), function (trx) {
      return Person
        .query(trx)
        .findById(req.params.id)
        .then(function (person) {
          if (!person) { throwNotFound(); }
          return person
            .$relatedQuery('movies', trx)
            .insert(req.body);
        });
    }).then(function (movie) {
      res.send(movie);
    }).catch(next);
  });
github contentjet / contentjet-api / dist / viewsets / MediaViewSet.js View on Github external
async update(ctx) {
        // Only description and tags are updatable. All other model fields are read-only.
        const errors = validate_1.default(ctx.request.body, updateConstraints);
        if (errors) {
            const err = new ValidationError_1.default();
            err.errors = errors;
            throw err;
        }
        const { tags, description } = ctx.request.body;
        const { project } = ctx.state;
        const data = {
            modifiedAt: moment().format(),
            description
        };
        const knex = Media_1.default.knex();
        return await objection_1.transaction(knex, async (trx) => {
            const media = await Media_1.default
                .query(trx)
                .patch(data)
                .returning('*')
                .where(`${this.modelClass.tableName}.id`, parseInt(ctx.params[this.getIdRouteParameter()], 10))
                .first();
            if (!media)
                throw new DatabaseError_1.default();
            let mediaTags = await MediaTag_1.default.bulkGetOrCreate(tags, project.id, trx);
            mediaTags = await media.setTags(mediaTags, trx);
            const mediaJSON = media.toJSON();
            mediaJSON.tags = mediaTags.map(mediaTag => mediaTag.name);
            ctx.body = mediaJSON;
            ctx.state.viewsetResult = {
                action: 'update',
                modelClass: this.modelClass,
github contentjet / contentjet-api / src / viewsets / MediaViewSet.ts View on Github external
async update(ctx: Koa.Context) {
    // Only description and tags are updatable. All other model fields are read-only.
    const errors = validate(ctx.request.body, updateConstraints);
    if (errors) {
      const err = new ValidationError();
      err.errors = errors;
      throw err;
    }
    const { tags, description } = ctx.request.body;
    const { project } = ctx.state;
    const data = {
      modifiedAt: moment().format(),
      description
    };
    const knex = Media.knex();
    return await transaction(knex, async trx => {
      const media = await Media
        .query(trx)
        .patch(data)
        .returning('*')
        .where(`${this.modelClass.tableName}.id`, parseInt(ctx.params[this.getIdRouteParameter()], 10))
        .first();
      if (!media) throw new DatabaseError();
      let mediaTags = await MediaTag.bulkGetOrCreate(tags, project.id, trx);
      mediaTags = await media.setTags(mediaTags, trx);
      const mediaJSON = media.toJSON();
      mediaJSON.tags = mediaTags.map(mediaTag => mediaTag.name);
      ctx.body = mediaJSON;
      ctx.state.viewsetResult = {
        action: 'update',
        modelClass: this.modelClass,
        data: mediaJSON
github strues / boldr / src / api / routes / auth / auth.controller.js View on Github external
bio: req.body.bio,
    website: req.body.website,
    profile_image: req.body.profile_image,
    birthday: req.body.birthday,
    facebook_profile: req.body.facebook_profile,
    linkedin_profile: req.body.linkedin_profile,
    github_profile: req.body.github_profile,
    google_profile: req.body.google_profile,
    twitter_profile: req.body.twitter_profile,
  };
  const checkExisting = await User.query().where('email', req.body.email);
  debug(checkExisting);
  if (checkExisting.length) {
    return next(new Conflict());
  }
  const newUser = await objection.transaction(User, async (User) => {
    const user = await User
        .query()
        .insert(userInfo);
    await user.$relatedQuery('role').relate({ id: 1 });

    if (!user) {
      throwNotFound();
    }
    // generate user verification token to send in the email.
    const verificationToken = await generateHash();
    // get the mail template
    const mailBody = await welcomeEmail(verificationToken);
    // subject
    const mailSubject = 'Boldr User Verification';
    // send the welcome email
    handleMail(user, mailBody, mailSubject);
github contentjet / contentjet-api / dist / viewsets / EntryViewSet.js View on Github external
const entryType = await EntryType_1.default.getById(entryTypeId);
        const { project, user } = ctx.state;
        if (!entryType || entryType.projectId !== project.id) {
            throw new ValidationError_1.default('Entry type with the provided id does not exist in project');
        }
        // Check the entry fields are valid against the entry type's fields
        await this.validateFields(entryType, fields, project.id);
        // Prepare the data for insertion into database
        const entryData = lodash_1.cloneDeep(ctx.request.body);
        delete entryData.tags;
        delete entryData.modifiedAt;
        entryData.userId = user.id;
        entryData.modifiedByUserId = user.id;
        entryData.fields = Entry_1.default.externalFieldsToInternal(entryType.fields, fields);
        const knex = Entry_1.default.knex();
        return await objection_1.transaction(knex, async (trx) => {
            // Create new entry
            const entry = await Entry_1.default.create(entryData, trx);
            if (!entry)
                throw new DatabaseError_1.default();
            // Get or create tags and relate them to entry
            let entryTags = await EntryTag_1.default.bulkGetOrCreate(tags, project.id, trx);
            entryTags = await entry.setTags(entryTags, trx);
            const entryJSON = entry.toJSON();
            entryJSON.tags = entryTags.map(entryTag => entryTag.name);
            entryJSON.fields = await entry.internalFieldsToExternal(entryType.fields, trx);
            ctx.body = entryJSON;
            ctx.state.viewsetResult = {
                action: 'create',
                modelClass: Entry_1.default,
                data: entryJSON
            };
github stelace / stelace / src / services / asset.js View on Github external
} = {}) => {
    try {
      const { Event, Asset } = await getModels({ platformId, env })

      if (typeof deltas === 'undefined') {
        const config = Event.getUpdatedEventDeltasConfig('asset')
        deltas = Event.getUpdatedEventDeltas(config, updateAttrsBeforeFullDataMerge || updateAttrs, asset)
      }

      const knex = Event.knex()
      const parentEventId = await getObjectId({ prefix: Event.idPrefix, platformId, env })

      // newAsset can be omitted for performance reasons
      const exposedNewAsset = newAsset ? Asset.expose(newAsset, { req, namespaces: ['*'] }) : {}

      await transaction(knex, async (trx) => {
        await bluebird.each(Object.keys(deltas), type => {
          const delta = deltas[type]

          return Event.createEvent({
            createdDate: eventDate,
            type,
            objectId: assetId,
            // not exposing object in child events with deltas only
            changesRequested: Asset.expose(delta, { req, namespaces: ['*'] }),
            parentId: parentEventId,
            // populate relatedObjectsIds
            _tmpObject: exposedNewAsset,
            metadata: eventMetadata
          }, { platformId, env, queryContext: trx })
        })
github stelace / stelace / src / services / transaction.js View on Github external
const {
      transactionId,
      name,
      data = {}
    } = req

    const currentUserId = getCurrentUserId(req)

    let updateAttrs
    let transaction
    let assetType
    let updatedTransaction

    const knex = Transaction.knex()

    await knexTransaction(knex, async (trx) => {
      transaction = await Transaction.query(trx).forUpdate()
        .findById(transactionId)
      if (!transaction) {
        throw createError(404)
      }
      if (!transaction.assetId) {
        throw createError(422, 'This transaction is not associated to an asset')
      }

      assetType = transaction.assetType
      let transactionProcess = assetType.transactionProcess
      if (!transactionProcess) {
        transactionProcess = getDefaultTransactionProcess()
      }

      const isOwner = transaction.ownerId === currentUserId
github stelace / stelace / src / services / transaction.js View on Github external
async function cancelTransactions ({ transactions, platformId, env, cancellationReason }) {
  const { Transaction, Event } = await getModels({ platformId, env })

  const knex = Transaction.knex()

  await knexTransaction(knex, async (trx) => {
    await bluebird.map(transactions, async (transaction) => {
      let transactionProcess

      if (transaction.assetType) {
        transactionProcess = transaction.assetType.transactionProcess
        if (!transactionProcess) {
          transactionProcess = getDefaultTransactionProcess()
        }
      } else {
        transactionProcess = getDefaultTransactionProcess()
      }

      const status = transactionProcess.cancelStatus
      const now = new Date().toISOString()

      const newStatusHistoryStep = { status, date: now }