
// rethink.<%- js %> - RethinkDB adapter
<%- tplTsOnly([`import { App } from './app.interface'${sc}`, '']) -%>
<%- tplImports('rethinkdbdash', 'rethinkdbdash', 'req') %>
<%- tplImports('logger', './logger') %>
<%- insertFragment('imports') %>
<%- insertFragment('init') %>

<%- tplExport('function (app) {', 'function (app: App) {') %>
  let config = app.get('rethinkdb')<%- sc %>
  let r = rethinkdbdash(config)<%- sc %>

  let oldSetup = app.setup<%- sc %>
  <%- insertFragment('func_init') %>

  app.set('rethinkdbClient', r)<%- sc %>

  app.setup = function (...args<%- tplTsOnly(': any[]') -%>) {
    let promise = Promise.resolve()<%- sc %>
    <%- insertFragment('func_init') %>

    // Go through all services and call the RethinkDB `init`
    // which creates the database and tables if they do not exist
    Object.keys(app.services).forEach(path => {
      let service = app.service(path)<%- sc %>

      if (typeof service.init === 'function') {
        promise = promise.then(() => { service.init()<%- sc %> }
          .catch(error => {
            console.log(error)<%- sc %>
            logger.error(error)<%- sc %>
          })
      }
    })<%- sc %>

    // Access the initialization if you want to run queries
    // right away that depend on the database and tables being created
    this.set('rethinkInit', promise)<%- sc %>

    <%- insertFragment('func_return') %>
    return oldSetup.apply(this, args)<%- sc %>
  }<%- sc %>
  <%- insertFragment('more') %>
}<%- tplJsOnly([sc]) %>
<%- insertFragment('funcs') %>
<%- insertFragment('end') %>
