
// mongodb.<%- js %> - MongoDB adapter
<%- tplTsOnly([`import { App } from './app.interface'${sc}`, '']) -%>
<%- tplImports('{ parseConnectionString }', 'mongodb-core', 'req') %>
<%- tplImports('{ MongoClient }', 'mongodb', 'req') %>
<%- tplImports('logger', './logger') %>
<%- insertFragment('imports') %>
<%- insertFragment('init') %>

<%- tplExport('function (app) {', 'function (app: App) {') %>
  let config = app.get('mongodb')<%- sc %>
  <%- insertFragment('func_init') %>

  const promise = MongoClient.connect(config, { useNewUrlParser: true, useCreateIndex: true }).then(client => {
    // For mongodb <= 2.2
    if (client.collection) {
      return client<%- sc %>
    }

    const dbName = parseConnectionString(config, () => {});
    return client.db(dbName)<%- sc %>
  })
    .catch(error => {
      console.log(error)<%- sc %>
      logger.error(error)<%- sc %>
    })<%- sc %>

  app.set('mongoClient', promise)<%- sc %>
  <%- insertFragment('more') %>
}<%- tplJsOnly([sc]) %>
<%- insertFragment('funcs') %>
<%- insertFragment('end') %>
