lowdb-models
TypeScript icon, indicating that this package has built-in type declarations

0.7.7 • Public • Published

lowdb-models

Simple model implementation to use with lowdb

Allows to check for data duplication, required values, and some other features

Install

npm install lowdb-models

Usage

Be aware that lowdb could change it's instance method

import { JSONFilePreset } from 'lowdb/node' // This could change
import { newModel } from 'lowdb-models'

Creating a model

var Posts = newModel({
  id: {
    required: true,
    unique: true
  },
  title: {
    required: true
  },
  author: {
    required: true
  }
}, {tableName: 'posts'})
// Lowdb instance
const db = await JSONFilePreset('db.json', {})

// Initialize the model
Posts.init(db)

Writing data

Posts.create({id: 1, title: 'Cool title', author: 'John'})

Model's data is kept inside it's tableName value

// db.json
{
  "posts": [
    { "id": 1, "title": "Cool title", "author": 'John' }
  ]
}

Retrieving data

Posts.findAll()
>> [{id: 1, title: 'Cool title', author: 'John'}] 
Posts.find({ title: 'title' })
Posts.findOne({ id: 1 })

Update

Posts.update({ id: 1},
  {
    title: 'New cool title'
  })

Deleting data

await Posts.remove({ id: 1 })
// Or
await Posts.remove({ title: 'New cool title' })

Generate property

Allow it to use a function wich will be execute before create and it return value is set to the property

Can be used to generate id

import { uuid } from 'uuidv4'

var Posts = newModel({
  id: {
    required: true,
    unique: true,
    generate: () => uuid()
  }
}, {tableName: 'posts'})

Package Sidebar

Install

npm i lowdb-models

Weekly Downloads

0

Version

0.7.7

License

ISC

Unpacked Size

14.6 kB

Total Files

11

Last publish

Collaborators

  • filipestudt