Create a sails.js hooks with models - sails.js

I want to create a sails.js hook which has it own model.
How can I inject this model into the current app ?
I've found this : https://github.com/leeroybrun/sails-hook-hookloader, but I don't understand how it work.
Thank you,

I've found an easy way to do it !
I've just created symlinks of all the hook models files to the main app "api/models" folder !
My initialize function look like that :
var path = require('path');
var fs = require('fs');
module.exports = function ToInitialize(sails) {
return function initialize(cb) {
// the path of the Hook model
var modelFile = path.join(__dirname, '../models/Model.js');
// the destination path
var modelFileDest = path.join(sails.config.appPath, 'api/models/Model.js');
if (!fs.existsSync(modelFileDest)) {
// create a symlink to the api/models folder
fs.symlink(modelFile, modelFileDest, 'file', cb);
} else {
return cb();
}
};
};

Related

Referencing local jQuery.sap.storage initialized in onInit in other functions

I'm attempting to use local storage to store variables used throughout a workflow. I initialize the local storage in the onInit function of my controller as shown below.
onInit: function () {
var data = {
"testItem" : [{
"priority" : 1,
"title" : "test1"
}]
}
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
this.getView().setModel(oModel, "testModel");
jQuery.sap.require("jquery.sap.storage");
var oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
if(oStorage.get("myLocalData")){
var oData = oStorage.get("myLocalData");
oModel.setData(oData);
}
}
Once this has been initiated it, how do I access that storage within other functions like an addItem function below?
addItem: function(evt){
var oView=this.getView();
var newItem = oView.byId("input").getValue();
var oModel = oView.getModel("testModel");
var oNew = {
testItem : {"priority" : 6, "title" :newItem }
};
var oData = oModel.getData();
oData.agendaItem.push(oNew);
oModel.refresh(true);
oStorage.put("myLocalData", oData); //this is where I'm unsure
}
Everything else (however hacky ;) ) works up to this point but I can't seem to wrap my head around accessing this local storage. Can I bind it with sap.ui.core or is it persistent in that my initial call in onInit is pointless and local storage is accessible at any point?
I appreciate your patience with me as I'm extremely new to the SAPUI5 library.
Ok so its as easy as it sounds. Using the line
jQuery.sap.storage(jQuery.sap.storage.Type.local).put("myLocalData", oData);
Puts the data in the local storage. Cheers!

How do I access environment variables in config SailsJS

I'm trying to access my environment variables inside a config file. Can I use this variable inside a config?
For example
// config/env/development.js
module.exports = {
appUrl: 'http://MY_DEV_PLACE/',
}
//config/passport.js
var appUrl = appUrl || sails.config.appUrl || 'localhost:1337'; //<-- sails is not defined
I also tried in local.js:
// config/local.js
module.exports = {
gAPI: { secret: 'aaa'}
}
//config/passport.js
var appUrl = gAPI || sails.config.gAPI || 'some pass'; //<-- sails is not defined
EDIT:
For appURL I'm using env like: APP_URL=http://example.com/api sails lift
For password I'm using:
var locals;
try {
locals = require('./local');
} catch (e) {
// not local so just ignore
}
module.exports.passport = {
'GoogleAPI.Password': locals ? locals.gAPI.secret : ’some key'
};
You can use the local.js file for environment variables. This file is discussed in-depth here. This is pretty much the go to for storing environment variables in sails.
Important caveats: make sure this file is included in your .gitignore file lest you risk exposing important information to the world, this file will need to be configured for each environment (e.g. local, staging, production), you can access your environment variables via sails.config.variable_name, this file will take priority over the development.js and production.js file in the /env/ sub-directory.
I accessed the sails object from the routes.js like this:
module.exports.routes = {
'/': (req, res) => {
res.redirect(sails.config.frontendUrl)
}
}
In config/global.js add the following line....
sails: true,
This makes sails instance global.

reference sails config outside module.exports

How can I use sails.config outside the module.exports? I'm trying to pass sails.config variables to another object, something like below;
var foo = new Foo(sails.config.myconf.myVar);
module.exports {
bar : function(){
// Use foo here
foo.blah();
}
};
(Same question also asked in a comment in this Create config variables in sails.js? See #jreptak comment)
Each files of Sails config is a module then if you want to use it, you just have to import it.
Here is an example to import Sails connections of sails.config.connections module.
Be careful about the path of the module in the require, it must be relative.
var connections = require('../../config/connections');
This was not possible in Sails v0.9. However, this is now possible in Sails v0.10 onwards.
Here's the specific issue on github: https://github.com/balderdashy/sails/issues/1672
So now you can do something like this:
//MyService.js
var client = new Client(sails.config.client);
module.exports = {
myMethod: function(callback){
client.doSomething();
}
}
If you're stuck with Sails v0.9, I would recommend that you follow the workaround specified in the github issue:
//MyService.js
var client;
module.exports = function(){
client = client || new Client(sails.config.client);
return {
myMethod: function(){
client.doSomething();
}
}
}
Which can be used like so:
//SomeController.js
module.exports = {
list: function(req,res){
MyService().myMethod();
}
}
You can't do this, if you want to access sails.config params you have to create a custom hook http://sailsjs.org/documentation/concepts/extending-sails/hooks and do your 'magic' in it

Is there a way to create and run a dynamic script from karma.conf.js

I'm using karma to run tests on an angularjs application.
There are a couple JavaScript functions that I would like to run at start-up, but they need to be dynamically created based on some system data. When running the app, this is handled with node.
Is there any way to create a script as a var and pass it to the files: [] rather than just using a pattern to load an existing file?
I can make this work by creating the file, saving it to disk then loading it normally, but that's messy.
You can create your own karma preprocessor script.
For a starting point use the following as example:
var fs = require('fs'),
path = require('path');
var createCustomPreprocessor = function (config, helper, logger) {
var log = logger.create('custom'),
// get here the configuration set in the karma.conf.js file
customConfig = config.customConfig || {};
// read more config here in case needed
...
// a preprocessor has to return a function that when completed will call
// the done callback with the preprocessed content
return function (content, file, done) {
log.debug('custom: processing "%s"\n', file.originalPath);
// your crazy code here
fs.writeFile(path.join(outputDirectory, name), ... , function (err) {
if (err) {
log.error(err);
}
done(content);
});
}
};
createCustomPreprocessor.$inject = ['config', 'helper', 'logger'];
module.exports = {
'preprocessor:custom': ['factory', createCustomPreprocessor]
};
Add a package.json with the dependencies and serve it as a module. ;)
For more examples have a look to more modules here: https://www.npmjs.org/search?q=karma%20preprocessor

Store file in Mongo's GridFS with ExpressJS after upload

I have started building a REST api using expressJS. I am new to node so please bear with me. I want to be able to let users upload a file directly to Mongo's GridFS using a post to the /upload route.
From what I understand in expressJS documentation the req.files.image object is available in the route after uploading, which also includes a path and filename attribute. But how can I exactly read the image data and store it into GridFS?
I have looked into gridfs-stream but I can't tie ends together. Do I first need to read the file and then use that data for the writestream pipe? Or can I just use the file object from express and use those attributes to construct a writestream? Any pointers would be appreciated!
Here's a simple demo:
var express = require('express');
var fs = require('fs');
var mongo = require('mongodb');
var Grid = require('gridfs-stream');
var db = new mongo.Db('test', new mongo.Server("127.0.0.1", 27017), { safe : false });
db.open(function (err) {
if (err) {
throw err;
}
var gfs = Grid(db, mongo);
var app = express();
app.use(express.bodyParser());
app.post('/upload', function(req, res) {
var tempfile = req.files.filename.path;
var origname = req.files.filename.name;
var writestream = gfs.createWriteStream({ filename: origname });
// open a stream to the temporary file created by Express...
fs.createReadStream(tempfile)
.on('end', function() {
res.send('OK');
})
.on('error', function() {
res.send('ERR');
})
// and pipe it to gfs
.pipe(writestream);
});
app.get('/download', function(req, res) {
// TODO: set proper mime type + filename, handle errors, etc...
gfs
// create a read stream from gfs...
.createReadStream({ filename: req.param('filename') })
// and pipe it to Express' response
.pipe(res);
});
app.listen(3012);
});
I use httpie to upload a file:
http --form post localhost:3012/upload filename#~/Desktop/test.png
You can check your database if the file is uploaded:
$ mongofiles list -d test
connected to: 127.0.0.1
test.png 5520
You can also download it again:
http --download get localhost:3012/download?filename=test.png