UNPKG

1.44 kBJavaScriptView Raw
1'use strict';
2
3const Promise = require('bluebird');
4const types = require('punchcard-content-types');
5const config = require('config');
6
7const tables = require('./database/tables');
8const schemas = require('./database/schemas');
9const utils = require('./utils');
10
11const knex = require('knex');
12
13const database = knex(config.knex);
14
15/**
16 * Initialize the database with provided schemas
17 *
18 * @returns {promise} - Configured knex object for use with the database
19 */
20const init = () => {
21 return types(null, config).then(cts => {
22 // Get Content Type fields
23 const contentSchema = utils.singleItem('name', 'content', schemas).fields;
24
25 // Filter out Content from Schemas
26 const schemata = schemas.filter(schema => {
27 if (schema.name === 'content') {
28 return false;
29 }
30
31 return true;
32 }).concat(cts.map(type => {
33 // Add Content schemas back to all schemata
34 return {
35 name: `content-type--${type.id}`,
36 fields: contentSchema,
37 };
38 }));
39
40 // Loop over all schema and create database tables
41 return Promise.map(schemata, schema => {
42 return tables.create(database, schema);
43 });
44 }).then(() => {
45 // Return the database object if a user would like to start working with it
46 return database;
47 }).catch(e => {
48 throw new Error(e);
49 });
50};
51
52// return Promise.map(schemas, schema => {
53
54// }
55
56module.exports = database;
57module.exports.init = init;