Skip to content

Concept :: Store

Alex Tan Hong Pin edited this page Apr 25, 2018 · 2 revisions

Store represents the data source, and contains operations for getting/setting data. Currently, there is no separation between read and writes, but can be separated to mimic CQRS or Vuex's getters and mutations concept.

The data source can be from:

  • cache
  • database
  • third-party apis through HTTP calls
  • in-memory

The idea of store is to based on the Repository Pattern, as defined by Eric Evens in his Domain Driven Design book.

export default function Store (db) {
  // When calling external services, prefix the function with fetch
  // e.g. When calling food service
  // async function fetchFood () {
  //  return request('http://localhost:3000/foods/1')
  // }

  // one, all, create, update, delete, count, search is reserved for DB only operation
  async function one (id) {
    const [rows] = await db.query('SELECT * FROM food WHERE id = ?', [id])
    return (rows && rows[0]) || null
  }

  async function all (params) {
    const [rows] = await db.query('SELECT * from food')
    return rows
  }

  async function create ({ id, name }) {
    const [rows] = await db.query('INSERT INTO food (id, name) VALUES (?, ?)', [id, name])
    return rows
  }

  return {
    one,
    all,
    create
  }
}

Usage

// Initialize a new store by passing the database connection through DI
const store = Store(db)

// Get the item with id = 1
await store.get(1)

// Create a new item with id = 2 and name = 'Durian'
await store.create({ id: 2, name: 'Durian' })
Clone this wiki locally