All Projects → baethon → kex

baethon / kex

Licence: MIT license
ORM-less for Knex

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to kex

BotBlock.org
BotBlock - The List of Discord Bot Lists and Services
Stars: ✭ 29 (+70.59%)
Mutual labels:  knex, knexjs
Pecee Pixie
Lightweight, easy-to-use querybuilder for PHP inspired by Laravel Eloquent - but with less overhead.
Stars: ✭ 19 (+11.76%)
Mutual labels:  models, query-builder
node-starter-kit
Node.js / GraphQL project template pre-configured with TypeScript, PostgreSQL, login flow, transactional emails, unit tests, CI/CD workflow.
Stars: ✭ 76 (+347.06%)
Mutual labels:  knex, knexjs
Evolutility Server Node
Model-driven REST or GraphQL backend for CRUD and more, written in Javascript, using Node.js, Express, and PostgreSQL.
Stars: ✭ 84 (+394.12%)
Mutual labels:  models, query-builder
typescript-api-starter
🔰 Starter for Node.js express API in Typescript 🚀
Stars: ✭ 72 (+323.53%)
Mutual labels:  knex, knexjs
thinkorm
A flexible, lightweight and powerful Object-Relational Mapper for Node.js. Support TypeScript!!
Stars: ✭ 33 (+94.12%)
Mutual labels:  knex, query-builder
nestjs-objection
Objection module for NestJS
Stars: ✭ 24 (+41.18%)
Mutual labels:  knex, knexjs
transformers-lightning
A collection of Models, Datasets, DataModules, Callbacks, Metrics, Losses and Loggers to better integrate pytorch-lightning with transformers.
Stars: ✭ 45 (+164.71%)
Mutual labels:  models
govote-api
Simple Node.js API to help people find locations to get PVCs and Vote in the upcoming Nigeria General Elections.
Stars: ✭ 15 (-11.76%)
Mutual labels:  knex
mlreef
The collaboration workspace for Machine Learning
Stars: ✭ 1,409 (+8188.24%)
Mutual labels:  models
translatable
Add multilingual support to your laravel 5 models
Stars: ✭ 34 (+100%)
Mutual labels:  models
back-boilerplate
A boilerplate for building RESTful APIs using Node.js, PostgreSQL, koa, knex, bookshelf.
Stars: ✭ 33 (+94.12%)
Mutual labels:  knex
database
A php class for managing and connecting to a database
Stars: ✭ 33 (+94.12%)
Mutual labels:  query-builder
cookbook
VueJS + NodeJS Evergreen Cookbook
Stars: ✭ 440 (+2488.24%)
Mutual labels:  knex
cqrs
A foundational package for Command Query Responsibility Segregation (CQRS) compatible with Laravel.
Stars: ✭ 37 (+117.65%)
Mutual labels:  query-builder
apollo-studio-community
🎡  GraphQL developer portal featuring an IDE (Apollo Explorer), auto-documentation, metrics reporting, and more. This repo is for issues, feature requests, and preview docs. 📬
Stars: ✭ 212 (+1147.06%)
Mutual labels:  query-builder
viziquer
Tool for Search in Structured Semantic Data
Stars: ✭ 12 (-29.41%)
Mutual labels:  query-builder
felicity
Javascript object constructors and sample data based on Joi schema.
Stars: ✭ 107 (+529.41%)
Mutual labels:  models
sea-query
🔱 A dynamic SQL query builder for MySQL, Postgres and SQLite
Stars: ✭ 595 (+3400%)
Mutual labels:  query-builder
indexeddb-orm
Indexed DB ORM
Stars: ✭ 53 (+211.76%)
Mutual labels:  query-builder

Node.js CI npm version

@baethon/kex

Kex is a query extension for Knex. It uses the concept of "model" from ORMs like Lucid, or Laravel Eloquent restricted only to make queries. It has support for scopes, plugins, relations, and many more.

Installation

Install the package:

npm i @baethon/kex

Set up Kex instance:

const knex = require('knex')({ /* ... */ })
const { Kex } = require('@baethon/kex')

const kex = new Kex({ knex })

Create first model:

const User = kex.createModel('User')

Making queries

Kex models uses the Knex query builder. To start the query, use query() method:

const usersList = await User.query()

The query object is chainable:

const activeUsers = await User.query()
  .where({ active: true })

In some cases, you can omit the query() method and start chaining using following methods:

  • where()
  • whereIn()
  • insert()
  • returning()
const activeUsers = await User.where({ active: true })

Unlike Knex, the models don't create a query when using other methods (e.g. andWhere()).

Creating new records

await User.insert({ name: 'Jon' })

As in Knex, you should use returning() when you want to receive the returning fields:

const [id] = await User.returning('id')
  .insert({ name: 'Jon' })

Updating records

User.where({ active: true })
  .update({ active: false })
  
// to make an update of a single item you can use
// following query
User.find(userId)
  .update({ active: true })

Scopes

Scope is a function that alters the query. You can chain them as other query methods.

Scopes are declared when creating a model:

const User = kex.createModel('User', {
  scopes: {
    active (qb) {
      qb.where('active', true)
    }
  }
})

const activeUsers = await User.query()
  .active()

Scopes can be used in the callbacks of where():

const usersList = await User.where(qb => {
  qb.active()
    .orWhere('role', 'admin')
})

Global scopes

Global scope is very similar to the regular scope. The main difference is that it's applied automatically to every query.

const User = kex.createModel('User', {
  globalScopes: {
    active (qb) {
      qb.where('active', true)
    }
  }
})

const activeUsers = await User.query()

It's possible to ignore the scope using withoutGlobalScope(), or withoutGlobalScopes() method:

const usersList = await User.query()
  .withoutGlobalScope('active')
  // alternative syntax:
  // .withoutGlobalScopes(['active'])

Other

Kex supports many other things:

Conventions

Kex uses naming conventions taken from Lucid, or Eloquent:

  • the table name is a snake_case version of the pluralized model name (e.g. users)
  • the primary key is always id
  • foreign keys (used in relations) are snake_case version of a table name (in singular form) postfixed with _id (e.g. user_id)
  • the pivot table is a snake_case version of related table names (in singular form) joined in alphabetical order (e.g. tag_user)

The naming is fully customizable.

Motivation

Full-blown ORMs offer fantastic features. Yet sometimes, it might be overkill for your application. What I needed is a customizable DBAL which wouldn't make too much magic behind the scenes. I wanted something like Knex, yet a little more robust.

Kex gives you the feeling of an ORM. However, it makes sure not to interfere with your work. Build a query and fetch the results. That's all. Don't worry about hydrated objects, results collections, or anything like that.

Testing

The test suite is a combination of unit tests and integration tests. The latter use by default an SQLite database, however, you can (and sometimes must) choose a different database backend.

To run tests:

yarn test

Running a single test suite with:

yarn test tests/path/to/test-file.test.js

Using different database backend

You need to install client dependency:

  • mysql for MySQL database
  • pg for PostgreSQL database

Then, start the database and set env variables. The test suite supports two env variables:

  • DB_CLIENT (either mysql or pg)
  • DB_URL (e.g. mysql://user:passwd@host:3306/db_name)
DB_CLIENT=mysql DB_URL=mysql://user:passwd@host:3306/db_name yarn test
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].