Skip to content
This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
Will Schmid edited this page Aug 29, 2020 · 3 revisions

Here's an example of integrating oreo with your app:

import oreo from 'oreo'
import fs from 'fs'
import path from 'path'
import models from './models'
import config from '../config'
import schema from '../config/schema.json'

let db
const NUMERIC_OID = 1700

export default function getDb () {
  if (db) return db

  const isProduction = (process.env.NODE_ENV === 'production')

  if (isProduction) {
    // skip schema auto-detection
    config.db.schema = schema
  }

  const startTime = Date.now()
  db = oreo({ ...config.db, models }, err => {
    db._driver.types.setTypeParser(NUMERIC_OID, Number)
    const initDuration = Date.now() - startTime
    if (err) {
      console.log('oreo:', err)
    } else {
      console.log(`oreo: initialized in ${initDuration}ms`)
    }

    db.discover(() => {
      if (isProduction) return
      // save the schema to disk
      const schemaFile = path.resolve(`${__dirname}/../config/schema.json`)
      const newSchema = JSON.stringify(db, null, 2)
      console.log(`oreo: writing ${schemaFile}`)
      fs.writeFileSync(schemaFile, newSchema)
    })
  })

  return db
}