npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

woowahan-orm

v2.0.1

Published

A very light promise-based Node.js ORM for MySQL

Downloads

11

Readme

woowahan-ORM

license version

WoowahanORM is a very light promise-based Node.js ORM for MySQL. It features simple Model Queries(INSERT, UPDATE, SELECT, DELETE), Validations for Types and synchronization for Migration. WoowahanORM follows Semantic Versioning.

Installation

$ npm i woowahan-ORM
# Also need to install mysql2
$ npm i mysql2

API

const woowahanORM = require('woowahan-orm')

Connecting a Database

To connect to the database, you must passdown the connection parameters to the woowahanORM instance.

woowahanORM(connectionParams, options)

woowahanORM({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
    },
    {
      sync: {
            force: false
      }
    }
)

options

| Name | Type | Attributes | Description | | -------- | ----------- | -------- | ----------- | | options | object | optional | A hash of options(currently only sync exists) | options.sync | object | optional, default: false| Sync this Model to the DB, that is create the table.

Sync

  • sync option not provided : no sync
  • sync with force false : create tables if not exist
  • sync with force true : drop and create tables

Defining a Table

After a connection is made, it is available to create Table Models extending WoowahanORM.Model

options

| Name | Type | Attribute | Description | | -------- | ----------- | -------- | ----------- | | attributes | object | required | A hash of attributes with dataType(Required), required(Optional), defaultValue(Optional) | defaultWhere | object | optional | A hash of attributes that should be always included in where.

defaultWhere is automatically added to where when find calls are called.

Example

const { Model, DataTypes } = require('woowahan-orm')

class Product extends Model {
  static init() {
    return super.init(
      {
        name: { dataType: DataTypes.STRING, required: true },
        brandName: { dataType: DataTypes.STRING, required: true },
        isFeatured: { dataType: DataTypes.BOOLEAN, defaultValue: true },
      },
      {
        isFeatured: false,
      }
    )
  }
}

module.exports = User

id, createdAt, updatedAt, isDeleted are auto-generated for every Model.

id: { dataType: DataTypes.INTEGER },
isDeleted: { dataType: DataTypes.BOOLEAN },
createdAt: { dataType: DataTypes.TIMESTAMP },
updatedAt: { dataType: DataTypes.TIMESTAMP },

Supported Types

Currently Woowahan ORM supports and validates those DataTypes.

BOOLEAN: "tinyint(1)",
INTEGER: "int(11)",
DATE: "date",
DATETIME: "datetime",
TIMESTAMP: "timestamp",
STRING: "varchar(255)",
TEXT: "text",

Validation

All of the input object is validated using the internal validation function.

Validation is done for every Input(create, update, findOne, fineAll).

Filtering not related input

Input not defined in the attributes will be not filtered.

Example

For Product Class example above, validation will be done like below.

const product = await Product.create({
  brandName: 'Innisfree',
  name: 'Green tea toner',
  wrong: 'this is wrong' // will be ignored
}) // will be successfully created

Type Check

If the input type for the according attribute is incorrect, then it throws 400 Error

Example

const product = await Product.create({
  brandName: 1, // wrong type which will cause 400 Error
  name: 'Green tea toner',
})

Query

Model.create

Builds a new model instance and calls save on it.

public static async create(values: object): Promise<Model>

Example

const jane = await User.create({ name: "Jane" });

Model.update

Update a model instance. Must pass id in the values.(BulkUpdate not supported)

public static async update(values: object): Promise<void>

Example

await User.update({ id: req.user.id, nickname: "Jane" });

Model.findAll

Find all model instances match the options.

public static async findAll(options: object): Promise<Array<Model>>

Params

| Name | Type | Attribute | Description | | -------- | ----------- | -------- | ----------- | | options | object | optional | A hash of options to describe the scope of the search | options.attributes | string | optional, default: '*' | A Comma Separated list of the attributes that you want to select | options.where | object | optional | A hash of attributes to describe your search (v 1.0.0 only Exact Match is supported) | options.rawWhere | string | optional | A raw subQuery you can put in where | options.sortBy | object | optional | Specifies an ordering. (object needs to has two keys attribute, order).

Example

const product = await Product.findAll({
  attributes: 'id, name, price'
  where: {
    brandName: 'Innisfree'
  }
  sortBy: {
    attribute: createdAt,
    order: 'DESC'
  }
})

// if need more detailed select query, use rawWhere.
const rawWhere = `year(date)=${where.year} AND month(date)=${where.month}`
cosnt monthlyExpenditure = await Expenditure.findAll({ '*', where: { userId: req.user.id }, rawWhere })

Model.findOne

Find the first model instance that matches the options.

public static async findAll(options: object): Promise<Model>

Params

Same with Model.findAll params.

Example

const user = await User.findOne({
  attributes: 'id, name, nickname'
  where: {
    githubId: 'zoomkoding'
  }
})

Model.delete

Delete a model instance with id.

Deleting doesn't delete the instance, it changes isDeleted attribute to true .

Find Queries will automatically ignore instances with isDeleted: true

public static async delete(id: number): Promise<void>

Examples

await History.delete(req.params.id)