How do I access environment variables in config SailsJS - sails.js

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.

Related

Is it possible to create a file with all my functions and read from from it in my specs?

I have some specs that are using the same functions, I would like to make one single file only for functions and read from this file while executing my scripts, would be that possible? if so.. how to do that?
During google searchers I found the "exports" to add in config file but didn't work (also I don't know how to call it from the config)
For example, I would like to add 2 functions in my config file (or separated file only for functions) and during any point of my execution, call it from the spec file:
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/');
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail(){
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
1 - How can I do that? (using "Suites" would be an option?)
2 - How to call them in my specs?
Thank you and have a good day!
As far as I know you cannot add utility functions that you want to use in your tests in the config file. The options in the config file are generally for setting up the testing environment.
You can however put your functions in a separate file and import that to use the functions. Below is an example of how to do that using js and Node's module exports, you can do something similar with ts using classes.
// utils.js
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/'); // nice Lenny face :)
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail() {
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
module.exports = {
loginAdminUserloginAdminUser: loginAdminUser,
accessHistoryViewDetail: accessHistoryViewDetail
}
Then in your spec file
import * as utils from './utils.js';
...
it('should ...', () => {
...
utils.accessHistoryViewDetail();
...
});
});
I hope that helps.

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

Create a sails.js hooks with models

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();
}
};
};

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

require.js synchronous loading

I'd like to define a module which computes a new dependancy, fetches it and then returns the result. Like so:
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
var name = get_config_name();
var config;
require.synchronous([configs / '+name'], function(a) {
config = defaults.extend(a);
});
return config;
});
Is there a way to do this or a better way to attack this problem?
You may try to use synchronous RequireJS call require('configs/'+get_config_name()), but it will load a module synchronously only if it is already loaded, otherwise it will throw an exception. Loading module/JavaScript file synchronously is technically impossible.
UPD: It's possible (see Henrique's answer) but highly unrecommended. It blocks JavaScript execution that causes to freezing of the entire page. So, RequireJS doesn't support it.
From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously.
AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously. The solution may be in using loader plugin (details here and here):
// config_loader.js
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
return {
load: function (resourceId, require, load) {
var config_name = 'configs/' + get_config_name();
require([config_name], function(config) {
load(defaults.extend(config));
})
}
}
});
// application.js
define(['config_loader!'], function(config) {
// code using config
});
If get_config_name() contains simple logic and doesn't depend on another modules, the better and simpler is calculating on the fly paths configuration option, or in case your config depends on context - map configuration option.
function get_config_name() {
// do something
}
require.config({
paths: {
'config': 'configs/' + get_config_name()
}
});
require(['application', 'defaults', 'config'], function(application, defaults, config) {
config = defaults.extend(config);
application.start(config);
});
Loading JavaScript synchronously is NOT technically impossible.
function loadJS(file){
var js = $.ajax({ type: "GET", url: file, async: false }).responseText; //No need to append
}
console.log('Test is loading...');
loadJS('test.js');
console.log('Test was loaded:', window.loadedModule); //loadedModule come from test.js