Giter VIP home page Giter VIP logo

nightmare-orm's Introduction

Nightmare ORM

Object Relational Mapping for Node.js and PostgreSQL insisted on Eloquent from php.

Introduction:

The Nightmare ORM provides a simple implementation of object relational mapping, for working with your database. Each database table has a corresponding Model (ECMAScript 6 class) which is used to interact with that table. Models allow you to query for data in your tables, as well as insert and update new records into the table. It is also safe because it prevents SQL injection.

Installation

  • using npm:

    npm install nightmare-orm --save
    
  • using yarn:

    yarn add nightmmare-orm
    

Dependency

This module depends of a pool connection generated by the npm module "pg" also known as node-postgres.

Defining Models

To get started, all models must extend or inherit from Nightmare. In their construction method, they must receive an "data" parameter in case they want that model with all the information in the database mapped.

Also in the same constructor must execute the constructor of the father super, which must receive two parameters, first the pool of connections of PostgreSQL, second the name of the table to which that model belongs and finally the attribute "data" of constructor of the model itself.

Let's see in the following example we will see how the model is defined Profile:

const { Pool } = require('pg');
const Nightmare = require('nightmmare-orm');

//PostgreSQL connection pool
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'database',
  password: '1',
  port: 5432
});

//Model
class Profile extends Nightmare {
  constructor(data = false) {
    //          table_name
    super(pool, 'profiles', data);
    this.fillable = [
      'fullname', 'age', 'description'
    ];
  }
  
  //...
}

Inserting, Updating Models and Deletes

Inserts

To create a new record in the database, create a new model instance, set attributes on the model, then call the save method

const profile = new Profile();
profile.fullname = 'john doe';
profile.age = 22;
await profile.save();

Updates

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method.

const profile = new Profile();

profile.find(1).then(myProfile => {
  myProfile.age = 25;
  myProfile.save();
});
// or use async/await
await profile.find(1);
profile.age = 26;
await profile.save();

Deleting Models

To delete a model, call the delete method on a model instance:

await profile.find(1);
profile.delete();

Query Builder

Nightmare's query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application.

const profile = new Profile();
try {
  const profiles = await profile.select('*').execute();
  console.log(profiles);
} catch(error) {
  console.log('Error: ', error);
}

the "execute" method in which it performs the query based on the methods and parameters previously used in the instance. This method ends with the operation of the queryBuilder and returns a Promise with the result.

Selects

Specifying A Select Clause

Of course, you may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query.

const profiles = await profile.select('fullname', 'age', 'description').execute();

Where Clauses

You may use the where method on a query builder instance to add where clauses to the query. The most basic call to where requires three arguments. The first argument is the name of the column. the second argument is the value to evaluate against the column. Finally, the third argument is an operator, which can be any of the database's supported operators. if the operator is equal ("=") the third parameter can be omitted

let profiles = await profile.select('fullname').where('age', 22, '!=').execute();

profiles = await profile.select('fullname').where('age', 20).execute();
profile = await  profile.select('*').where('id', 20).limit(1).execute();

Of course, you may use a variety of other operators when writing a where clause:

const user = new User();
const chat = new Chat();
const userId = 22;
const users = await user.where('votes', 100, '>=').execute();
const users = await user.where('votes', 100, '<>').execute();
// json colunms
const message = await chat
  .select("content->'messages'")
  .where("content->'users'", userId, '@>')
  .execute();

// WHERE AND
const data = await  profile
  .where('age', 20)
  .where('fullname', 'john doe', '!=')
  // you can use any numbers of where's
  .orderBy('age', 'desc')
  .limit(10)
  .execute();

Joins

Inner Join Clause

The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:

const data = await user
  .select('users.*', 'contacts.phone', 'orders.price')
  .join('contacts', 'users.id', 'contacts.user_id', '=')
  .join('orders', 'users.id', 'orders.user_id', '=')
  .execute();

if the operator is equal ("=") this parameter can be omitted

JSON and JSONB

toJson()

You can get the data of an instance in json format using the toJson method, and thus leave aside all the information of methods and properties that the instance contains:

let user = new User();
user = await user.find(2);
user = user.toJson();

Using literal objects

If we have the chats table, which is structured as follows:

chat
id int
created_at timestamp
content jsonb or json

generate a javascript object I have installed it directly in an orm query:

const newChat = new Chat();
newChat.created_at = '2004-10-19 10:23:54';
newChat.content = {
  users: [1, 7, 6],
  messages: [
    { text: 'hello', user: 1 },
    { text: 'world', user: 7 }
  ],
  messageCounter: 2
};
await newChat.save();

const chatToUpdate = await chat.find(1);
chatToUpdate.content.messages.push({ text: 'yeah!', user: 6 });
chatToUpdate.content.messageCounter += 1;
await chatToUpdate.save();

the documentation is not yet ready, we are working on it

nightmare-orm's People

Contributors

fveracoechea avatar

Stargazers

 avatar  avatar

Watchers

 avatar

nightmare-orm's Issues

Pending to develop: Pagination Method

Currently the module does not have a method that allows paging the results of a query. Even if it has an interface developed to implement SQL statements "LIMIT" and "OFFSET".

For now, the project has the highest priority in developing the interface for SQL statements "JOIN ON". When ready, this feature will be added.

Pending to develop: Query Builder for "JOIN ON"

In this version of the project there is nothing else with a constructor of queries for SQL statements JOIN ON.

We are currently working on it, when the development is finished and the testing of this feature will be imbued with the QueryBuilder of this module.

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.