Load Mongoose instead of Bookshelf

This commit is contained in:
Aurélien Georget 2016-07-12 11:15:01 +02:00
parent 8cbe59a955
commit 756dd5407a
9 changed files with 518 additions and 7 deletions

View File

@ -22,7 +22,6 @@ module.exports = scope => {
// To determine the Strapi dependency to inject
// in the newly created `package.json`.
const frameworkPkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', 'strapi', 'package.json'))) || {};
const knexPkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', 'strapi-knex', 'package.json'))) || {};
// Finally, return the JSON.
return _.merge(scope.appPackageJSON || {}, {
@ -33,12 +32,9 @@ module.exports = scope => {
'dependencies': {
'async': getDependencyVersion(frameworkPkg, 'async'),
'lodash': getDependencyVersion(frameworkPkg, 'lodash'),
'knex': getDependencyVersion(knexPkg, 'knex'),
'socket.io': getDependencyVersion(frameworkPkg, 'socket.io'),
'sqlite3': getDependencyVersion(knexPkg, 'sqlite3'),
'strapi': getDependencyVersion(cliPkg, 'strapi'),
'strapi-bookshelf': getDependencyVersion(cliPkg, 'strapi-bookshelf'),
'strapi-knex': getDependencyVersion(cliPkg, 'strapi-knex')
'strapi-mongoose': getDependencyVersion(cliPkg, 'strapi-mongoose')
},
'main': './server.js',
'scripts': {

View File

@ -0,0 +1,16 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

94
packages/strapi-mongoose/.gitignore vendored Normal file
View File

@ -0,0 +1,94 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
.tmp
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history

View File

@ -0,0 +1,101 @@
############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
.tmp
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
############################
# Tests
############################
test

View File

@ -0,0 +1,9 @@
# MIT License
Copyright © 2015-2016 Wistity.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,21 @@
# strapi-mongoose
[![npm version](https://img.shields.io/npm/v/strapi-mongoose.svg)](https://www.npmjs.org/package/strapi-mongoose)
[![npm downloads](https://img.shields.io/npm/dm/strapi-mongoose.svg)](https://www.npmjs.org/package/strapi-mongoose)
[![npm dependencies](https://david-dm.org/wistityhq/strapi-mongoose.svg)](https://david-dm.org/wistityhq/strapi-mongoose)
[![Build status](https://travis-ci.org/wistityhq/strapi-mongoose.svg?branch=master)](https://travis-ci.org/wistityhq/strapi-bookshelf)
[![Slack status](http://strapi-slack.herokuapp.com/badge.svg)](http://slack.strapi.io)
This built-in hook allows you to use the [Mongoose ORM](http://mongoosejs.com/).
[Mongoose ORM](http://mongoosejs.com/) provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
## Resources
- [MIT License](LICENSE.md)
## Links
- [Strapi website](http://strapi.io/)
- [Strapi community on Slack](http://slack.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)

View File

@ -0,0 +1,222 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const mongoose = require('mongoose');
const pluralize = require('pluralize');
// Strapi helpers for models.
const utilsModels = require('strapi/lib/configuration/hooks/models/utils/');
/**
* Bookshelf hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
defaultConnection: 'default'
},
/**
* Initialize the hook
*/
initialize: function (cb) {
let globalName;
// Connect to mongo database
mongoose.connect('mongodb://localhost/test');
const db = mongoose.connection;
console.log("Strapi mongoose");
// Handle error
db.on('error', error => {
cb(error);
});
// Handle success
db.on('open', () => {
// Initialize collections
_.set(strapi, 'mongoose.collections', {});
// Return callback if there is no model
if (_.isEmpty(strapi.models)) {
return cb();
}
const loadedHook = _.after(_.size(strapi.models), function () {
cb();
});
// Parse every registered model.
_.forEach(strapi.models, function (definition, model) {
globalName = _.capitalize(definition.globalId);
// Make sure the model has a table name.
// If not, use the model name.
if (_.isEmpty(definition.collectionName)) {
definition.collectionName = model;
}
// Make sure the model has a connection.
// If not, use the default connection.
if (_.isEmpty(definition.connection)) {
definition.connection = strapi.config.defaultConnection;
}
// Make sure this connection exists.
if (!_.has(strapi.config.connections, definition.connection)) {
strapi.log.error('The connection `' + definition.connection + '` specified in the `' + model + '` model does not exist.');
strapi.stop();
}
// Add some informations about ORM & client connection
definition.orm = 'mongoose';
definition.client = _.get(strapi.config.connections[definition.connection], 'client');
// Register the final model for Bookshelf.
const loadedModel = definition.attributes;
// Initialize the global variable with the
// capitalized model name.
global[globalName] = {};
// Call this callback function after we are done parsing
// all attributes for relationships-- see below.
const done = _.after(_.size(definition.attributes), function () {
try {
// Initialize lifecycle callbacks.
loadedModel.initialize = function () {
const self = this;
const lifecycle = {
creating: 'beforeCreate',
created: 'afterCreate',
destroying: 'beforeDestroy',
destroyed: 'afterDestroy',
updating: 'beforeUpdate',
updated: 'afterUpdate',
fetching: 'beforeFetch',
fetched: 'afterFetch',
saving: 'beforeSave',
saved: 'afterSave'
};
_.forEach(lifecycle, function (fn, key) {
if (_.isFunction(strapi.models[model.toLowerCase()][fn])) {
self.on(key, strapi.models[model.toLowerCase()][fn]);
}
});
};
const schema = mongoose.Schema(loadedModel.attributes);
console.log(schema);
global[globalName] = mongoose.model(globalName, schema);;
// Push model to strapi global variables.
strapi.mongoose.collections[globalName.toLowerCase()] = global[globalName];
// Push attributes to be aware of model schema.
strapi.mongoose.collections[globalName.toLowerCase()]._attributes = definition.attributes;
loadedHook();
} catch (err) {
strapi.log.error('Impossible to register the `' + model + '` model.');
strapi.log.error(err);
strapi.stop();
}
});
if (_.isEmpty(definition.attributes)) {
done();
}
// Add every relationships to the loaded model for Bookshelf.
// Basic attributes don't need this-- only relations.
_.forEach(definition.attributes, function (details, name) {
const verbose = _.get(utilsModels.getNature(details, name), 'verbose') || '';
// Build associations key
if (!_.isEmpty(verbose)) {
utilsModels.defineAssociations(globalName, definition, details, name);
}
switch (verbose) {
case 'hasOne':
const FK = _.findKey(strapi.models[details.model].attributes, function (details) {
if (details.hasOwnProperty('model') && details.model === model && details.hasOwnProperty('via') && details.via === name) {
return details;
}
});
loadedModel[name] = {
type: Schema.Types.ObjectId,
ref: strapi.models[details.model].attributes[FK].model
};
break;
case 'hasMany':
const FK = _.findKey(strapi.models[details.collection].attributes, function (details) {
if (details.hasOwnProperty('collection') && details.collection === model && details.hasOwnProperty('via') && details.via === name) {
return details;
}
});
loadedModel[name] = [{
type: Schema.Types.ObjectId,
ref: strapi.models[details.model].attributes[FK].collection
}];
break;
case 'belongsTo':
const FK = _.findKey(strapi.models[details.model].attributes, function (details) {
if (details.hasOwnProperty('model') && details.model === model) {
return details;
}
});
loadedModel[name] = {
type: Schema.Types.ObjectId,
ref: strapi.models[details.model].attributes[FK].model
};
break;
case 'belongsToMany':
const FK = _.findKey(strapi.models[details.collection].attributes, function (details) {
if (details.hasOwnProperty('model') && details.collection === model) {
return details;
}
});
loadedModel[name] = [{
type: Schema.Types.ObjectId,
ref: strapi.models[details.model].attributes[FK].collection
}];
break;
default:
break;
}
done();
});
});
});
}
};
return hook;
};

View File

@ -0,0 +1,53 @@
{
"name": "strapi-mongoose",
"version": "2.0.0",
"description": "Mongoose hook for the Strapi framework",
"homepage": "http://strapi.io",
"keywords": [
"mongoose",
"hook",
"orm",
"nosql",
"strapi"
],
"directories": {
"lib": "./lib"
},
"main": "./lib",
"dependencies": {
"mongoose": "~4.5.4",
"lodash": "~4.6.1",
"pluralize": "~1.2.1",
"strapi": "~2.0.0"
},
"strapi": {
"isHook": true
},
"scripts": {
"prepublish": "npm prune"
},
"author": {
"email": "hack@wistity.co",
"name": "Wistity team",
"url": "http://wistity.co"
},
"maintainers": [
{
"name": "Wistity team",
"email": "hack@wistity.co",
"url": "http://wistity.co"
}
],
"repository": {
"type": "git",
"url": "git://github.com/wistityhq/strapi.git"
},
"bugs": {
"url": "https://github.com/wistityhq/strapi/issues"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"license": "MIT"
}

View File

@ -65,14 +65,13 @@
"lodash": "~4.6.1",
"node-schedule": "~1.1.0",
"socket.io": "~1.4.5",
"strapi-bookshelf": "~2.0.0",
"strapi-generate": "~2.0.0",
"strapi-generate-api": "~2.0.0",
"strapi-generate-migrations": "~2.0.0",
"strapi-generate-new": "~2.0.0",
"strapi-generate-policy": "~2.0.0",
"strapi-generate-service": "~2.0.0",
"strapi-knex": "~2.0.0",
"strapi-mongoose": "~2.0.0",
"strapi-utils": "~2.0.0"
},
"scripts": {