Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const moment = require('moment');
- const _ = require('lodash');
- const Promise = require('bluebird');
- const knex = require('knex')({
- client: 'pg',
- version: '9.6',
- connection: {
- user: 'postgres',
- password: '',
- database: 'bookshelf-test',
- },
- });
- const bookshelf = require('bookshelf')(knex);
- // Datetime conversion plugin
- const datetimePlugin = bookshelf => {
- bookshelf.Model = bookshelf.Model.extend({
- parse: attrs => {
- const data = _.mapValues(attrs, (val, key) => {
- if (key === 'updated_at' || key === 'created_at') {
- return moment(val).valueOf();
- }
- return val;
- });
- return data;
- },
- });
- };
- bookshelf.plugin(['registry', datetimePlugin]);
- // Models
- const UserModel = bookshelf.Model.extend({
- tableName: 'users',
- hasTimestamps: true,
- });
- Promise.all([
- knex.schema.hasTable('users', exists => {
- console.log(exists);
- if (!exists) {
- return knex.schema.createTable('users', table => {
- table.increments();
- table.string('name');
- table.timestamps(true, true);
- });
- }
- }),
- ])
- .then(() => {
- return [
- knex('users').insert({ name: 'John' }),
- knex('users').insert({ name: 'Jen' }),
- knex('users').insert({ name: 'Jimmy' }),
- ];
- })
- .spread(() => {
- return UserModel.fetchAll();
- })
- .then(users => {
- console.log(users.toJSON());
- })
- .then(() => {
- console.log('All done!');
- })
- .catch(error => {
- console.log(error);
- })
- .finally(() => {
- process.exit();
- });
Add Comment
Please, Sign In to add comment