Socket
Socket
Sign inDemoInstall

query-orm

Package Overview
Dependencies
11
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    query-orm

Loopback like ORM built to work with any node.js framework.


Version published
Weekly downloads
1
decreased by-75%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

query-orm

Loopback like ORM built to work with any node.js framework.

npm version

Installation

npm i query-orm

Usage

app.js

const QueryORM = require('query-orm');

const app = new QueryORM({
  appRoot: DIRNAME,
  modelConfig: './model-config.json',
  dataSources: './datasource.json'
});

app.on('model-init', (data) => {
  console.log(data);
});

app.on('error', (error) => {
  console.log(error);
});

async function createUser (data) {
  const createdUser = await app.models.User.create(data);
  return createdUser;
}

createUser({
  firstname: 'Bharath',
  lastname: 'Reddy',
  username: 'bharathreddy',
  password: 'Test@1234'
}).then((createdUser) => {
  console.log(createdUser)
}).catch((error) => {
  console.log(error);
});

app.models.User.find({
  where: {
    username: 'bharathreddy'
  }
}).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error);
});

datasources.json

{
  "testdatasource": {
    "name": "testdatasource",
    "settings": {
      "indexName": "testindex",
      "isAlias": false,
      "isPattern": false,
      "mappings": {
        "properties": {
          "docType": {
            "type": "keyword"
          },
          "userId": {
            "type": "keyword"
          },
          "username": {
            "type": "keyword"
          },
          "firstname": {
            "type": "keyword"
          },
          "lastname": {
            "type": "keyword"
          },
          "password": {
            "type": "keyword"
          },
          "created": {
            "type": "date"
          },
          "updated": {
            "type": "date"
          }
        }
      },
      "aliases": {},
      "indexSettings": {
        "number_of_shards": 1,
        "number_of_replicas": 2
      },
      "createIndex": true,
      "updateMapping": true,
      "version": 7,
      "defaultLimit": 200,
      "configuration": {
        "nodes": [
          "https://localhost:9200"
        ],
        "requestTimeout": 30000,
        "pingTimeout": 3000,
        "auth": {
          "username": "admin",
          "password": "admin"
        },
        "agent": {
          "maxSockets": 1,
          "keepAlive": false
        },
        "ssl": {
          "rejectUnauthorized": false
        },
        "sniffInterval": 10000
      }
    },
    "connector": "query-orm-connector-elastic",
    "localConnector": false
  }
}

model-config.json

{
  "directory": "./models",
  "models": {
    "User": {
      "dataSource": "testdatasource"
    }
  }
}

models/user.json

{
  "name": "User",
  "plural": "users",
  "validations": {},
  "id": {
    "property": "userId",
    "generated": true
  },
  "schema": {
    "type": "object",
    "properties": {
      "userId": {
        "type": "string"
      },
      "username": {
        "type": "string"
      },
      "password": {
        "type": "string"
      },
      "firstname": {
        "type": "string"
      },
      "lastname": {
        "type": "string"
      },
      "created": {
        "type": "string",
        "format": "date-time"
      },
      "updated": {
        "type": "string",
        "format": "date-time"
      }
    },
    "required": [
      "firstname",
      "lastname",
      "userId",
      "username",
      "password"
    ]
  },
  "relations": {}
}

Model Methods

find

This method is for fetching data from Model's dataSource based on given query filter.

Example:

await app.models.User.find({
  where: {
    firstname: 'bharath'
  },
  limit: 100,
  skip: 10
})

findOne

This method is for fetching only one matched record from Model's dataSource based on given query filter.

limit and skip options will not work here.

Example:

await app.models.User.findOne({
  where: {
    firstname: 'bharath'
  }
})

findById

This method is for fetching the record from Model's dataSource based on given id parameter.

limit and skip options will not work here.

Example:

await app.models.User.findById('id123');

count

This method is for fetching the count from Model's dataSource based on given query filter.

limit and skip options will not work here.

Example:

await app.models.User.count({
  firstname: 'bharath'
});

create

This method is for create a record in Model.

Example:

await app.models.User.create({
  firstname: 'bharath'
});

updateById

This method is for updating a record matching the given id with attributes object provided.

Example:

await app.models.User.updateById('id123', {
  firstname: 'bharath'
});

updateByQuery

This method is for updating multiple records matched for given query with attributes object provided.

Example:

await app.models.User.updateByQuery({
  and: [{
    lastname: 'reddy'
  }, {
    firstname: 'test'
  }]
}, {
  firstname: 'bharath'
});

deleteById

This method is for deleting a record that matches the given id.

Example:

await app.models.User.deleteById('id123');

deleteByQuery

This method is for deleting multiple records that matches the given query.

Example:

await app.models.User.updateByQuery({
  and: [{
    lastname: 'reddy'
  }, {
    firstname: 'test'
  }]
});

Querying Data

Base Filters

{
  "where": {},
  "limit": 100,
  "skip": 2, // offset
  "searchafter": [], // optional for pagination
  "order": [], // [] or ""
  "fields": [], // [] or ""
  "include": [], // [] or "" for relations
}

where is the main query attribute. It supports and and or queries.

Relations

Connectors

OperationalHooks

before save

This hook will be triggered before execute of methods (create, updateById and updateByQuery).

Example:

  //create
  Model.observe('before save', async (instance) => {
    instance.foo = 'bar1';
    return Promise.resolve();
  })
  
    //update
  Model.observe('before save', async (data) => {
    // data.id, data.attributes, data.where are available w.r.t method
    return Promise.resolve();
  })

after save

This hook will be triggered after execute of methods (create, updateById and updateByQuery).

Example:

  Model.observe('after save', async (ctx) => {
    //ctx.instance will be result and isNewInstance is also available on ctx
    return Promise.resolve();
  })

before delete

This hook will be triggered before execute of methods (deleteById and deleteByQuery).

Example:

  Model.observe('before delete', async (data) => {
    // data.id, data.attributes, data.where are available w.r.t method
    return Promise.resolve();
  })

after delete

This hook will be triggered after execute of methods (deleteById and deleteByQuery).

Example:

  Model.observe('after delete', (ctx) => {
    //ctx.instance will be result
    return Promise.resolve();
  })

Keywords

FAQs

Last updated on 15 Jul 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc