Skip to content

wangzuo/tinyrecord

Repository files navigation

tinyrecord

npm Build Status codecov styled with prettier

[wip] ActiveRecord in node

Installation

yarn add tinyrecord
# npm i tinyrecord --save

# sqlite
yarn add better-sqlite3

# mysql
yarn add mysql2

Establish connection

const { Base } = require('tinyrecord');

// yarn add sqlite3
Base.establishConnection({
  adapter: 'sqlite3',
  database: ':memory:'
});

// yarn add mysql2
Base.establishConnection({
  adapter: 'mysql2',
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'tinyrecord'
});

Model

const { Base } = require('tinyrecord');

class Post extends Base {}
Post.tableName = 'posts';

module.exports = Post;

Crud

const post = await Post.new({ title: 'hello' });
await post.save();

const post = await Post.create({ title: 'hello' });
await post.update({ title: 'world' });

Find

const post = await Post.find(1);
const post = await Post.findBy({ title: 'hello' });
const post = await Post.findOrCreateBy({ title: 'hello' });

Query

const sql = await Post.order({ id: 'asc' }).toSql();
const posts = await Post.limit(10).records();

Migration

const { Migration } = require('tinyrecord');

class CreatePosts extends Migration {
  async change() {
    await this.createTable('posts', {}, t => {
      t.string('title');
      t.text('content');
      t.timestamps();
    });
  }
}

Commands

tiny db:create
tiny db:drop
tiny db:migrate
tiny db:migrate:reset
tiny migration:create AddTitleToPosts title:string
tiny model:create Post title:string

License

MIT