Giter VIP home page Giter VIP logo

objection-unique's Introduction

Unique validation for Objection.js

npm node Build Status Coverage Status

This plugin adds a unique validation for Objection.js models.

NOTE: Unique validation at update only works with $query methods.

Installation

NPM

npm i objection-unique --save

Yarn

yarn add objection-unique

Usage

Mixin the plugin

// Import objection model.
const Model = require('objection').Model;

// Import the plugin.
const unique = require('objection-unique')({
  fields: ['email', 'username', ['phone_prefix','phone_number']],
  identifiers: ['id']
});

// Mixin the plugin.
class User extends unique(Model) {
  static get tableName() {
    return 'User';
  }
}

Validate insert

/**
 * Insert.
 */

// Insert one user.
await User.query().insert({ email: 'foo', username: 'bar' });

try {
  // Try to insert another user with the same data.
  await User.query().insert({ email: 'foo', username: 'bar' });
} catch (e) {
    // Exception with the invalid unique fields
    //
    // {
    //   email: [{
    //     keyword: 'unique',
    //     message: 'email already in use.'
    //   }],
    //   username: [{
    //     keyword: 'unique',
    //     message: 'username already in use.'
    //   }
    // }
}

Validate update/patch

/**
 * Update/Patch.
 */

// Insert one user.
await User.query().insert({ email: 'foo', username: 'bar' });

// Insert the user that we want to update.
const user = await User.query().insertAndFetch({ email: 'biz', username: 'buz' });

try {
  user.$query().update({ email: 'foo', username: 'buz' });
  // user.$query().patch({ email: 'foo' });
} catch (e) {
  // Exception with the invalid unique fields
  //
  // {
  //   email: [{
  //     keyword: 'unique',
  //     message: 'email already in use.'
  //   }]
  // }
}

Options

fields: The unique fields. Compound fields can be specified as an array

identifiers: The fields that identifies the model. (Default: ['id'])

These options can be provided when instantiating the plugin:

const unique = require('objection-unique')({
  fields: ['email', 'username', ['phone_prefix', 'phone_number']],
  identifiers: ['id']
});

Tests

Run the tests from the root directory:

npm test

Contributing & Development

Contributing

Found a bug or want to suggest something? Take a look first on the current and closed issues. If it is something new, please submit an issue.

Develop

It will be awesome if you can help us evolve objection-unique. Want to help?

  1. Fork it.
  2. npm install.
  3. Hack away.
  4. Run the tests: npm test.
  5. Create a Pull Request.

objection-unique's People

Contributors

dawaa avatar dsego avatar joaonice avatar nunorafaelrocha avatar nunovieira220 avatar patricklef avatar trey-baker avatar vonagam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

objection-unique's Issues

Unique together

It seems that this plugin ensures that values from the fields specified are each unique on the table. How would I go about using this plugin to ensure that the values of my fields are unique together in the table, but each is not forced to be unique on its own? Thank you for your help, and thank you for the work you've put in on this plugin!

Model extension should be anonymous

Hi!

First of all, thank you for building this plugin for objection. Having a collection of good quality plugins such as this one for the most common problems will do a lot of good for the objection ecosystem.

Objection changed its best practices regarding the name of the extending class returned from the mixin function. The class should not have a name. The reason for this change is explained in this issue.

Please consider updating your plugin to follow the updated practices.

ES6 import syntax

I am trying to use this module with the 'import' syntax, but the compiler complains that the resulting model does not contain a query() method.

import uniqueFn from 'objection-unique'
const unique = uniqueFn({
  fields: ['email']
})
export default class User extends unique(Model) {

What is the proper way to import it?

Doesn't work with graph inserts?

I added objection-unique to my Users model to make user email addresses unique:

const unique = require('objection-unique')({
  fields: ['email'],
  identifiers: ['id']
});

However when I do a graph insert in my Account model as shown below to insert an account and related user, I get a database error due to the Postgres unique constraint, objection-unique doesn't seem to be doing anything:

  static createAccount(firstName, lastName, email, password, trialEnds) {
    return this.query().insertGraph({
      trialEnds,
      users: [
        {
          firstName,
          lastName,
          email,
          password
        }
      ]
    });
  }

Is this a known limitation of objection-unique that it doesn't work with graph inserts, or am I doing something wrong?

TypeScript types declaration file

This npm package needs a TypeScript types declaration file so that developers who enjoy writing with TS can use it with this package and have a better development experience. Would you like me to write one?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.