I'm pretty new to web dev and AngularJS. I'm trying to figure out how to use services and I'm following this tutorial: http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application
How does the service connect with the controller? Is this done implicitly? I understand that you can inject the service into the controller, but how is it being done in the tutorial?
You inject your service into your controller. Like this. The reason behind services are that you want to keep your controller as 'skinny' as possible. All heavy logic/requests should be outsourced to the service.
app.service('myService', function(){
this.name = 'Tyler';
}
app.controller('myCtrl', function($scope, myService){
$scope.name = myService.name;
}
Another benefit of using a service is that you could inject that service into more than one controller. A good example is if you had a service that made a HTTP request. Instead of recreating the same code in every controller to make the request, you could simply create a service that did the request and inject that service into every controller you needed that functionality.
edit: To answer your question. You need to be sure to place the service in the controller on the same 'module'. Meaning. In your HTML you have something like this.
<body ng-app="myApp">
That's telling the whole BODY that whatever is nested inside it belongs to the 'myAPP' app. Then you usually have an app.js file that has something like this.
var app = angular.module('myApp', []);
Notice that the angular.module takes two parameters. You're telling angular to create a new app called 'myApp' (which coincides with your HTML).
Then in your controller, service, directive files you'll have something like this at the top.
var app = angular.module('myApp');
Notice this one is only taking one parameter, the name of the app. You're telling angular that instead of creating a new app, you're going and 'getting' the one you already build. You'll then stick your controllers, directives, services on this app and as long as things are on the same app, you'll be able to inject them.
Another EDIT to your comment.
In the tutorial they're doing it a little weird. They're creating new modules for every controller, service, etc. It's not bad, just different. Doing it this way confuses me so I just prefer to stick everything under one module. In the tutorial this is the line that's gluing it all together.
// public/js/app.js
angular.module('sampleApp', ['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService', 'GeekCtrl', 'GeekService']);
They have a sampleApp then all there other modules they build are being injected into the main sample app.
a service means to be accesible from all controllers, a service is a constructor, every controller can read or write in a service, in order to use a service you must call a service in this way:
var app = angular.module('myApp', []);
app.service('sharedProperties', function() {
var stringValue = 'test string value';
var objectValue = {
data: 'test object value'
};
return {
getString: function() {
return stringValue;
},
setString: function(value) {
stringValue = value;
},
getObject: function() {
return objectValue;
}
}
});
app.controller('myController1', function($scope, sharedProperties) {
$scope.setOnController1 = function(sharedPoperties){
$scope.stringValue = sharedProperties.getString();
$scope.objectValue = sharedProperties.getObject().data;
}
});
app.controller('myController2', function($scope, sharedProperties) {
$scope.stringValue = sharedProperties.getString;
$scope.objectValue = sharedProperties.getObject();
$scope.setString = function(newValue) {
$scope.objectValue.data = newValue;
sharedProperties.setString(newValue);
//some code to set values on screen at controller1
};
});
Here is the JS FIDDLE
http://jsfiddle.net/b2fCE/228/
Related
As far as I can understand, Clean Architecture/DDD states that your use cases can be triggered by anything, let it be a HTTP request or GUI, correct?
I am trying to emulate that, but I am not really sure if I am doing it correctly.
Inside my infrastructure folder, I have routers. For example:
import express from 'express'
import UserController from '../controllers/user_controller.js'
import ExpressRouterAdapter from './ExpressRouterAdapter.js'
export default function UsersRouter () {
const router = express.Router()
router.route('/:username').get(ExpressRouterAdapter.adapt(UserController.getUser))
return router
}
(ExpressRouterAdapter is just an adapter that transforms Express requests into a simple httpRequest JS object)
And here is my GetUser controller:
export class GetUser {
constructor ({ FindUserService }) {
this.findUser = FindUserService
}
async handle (httpRequest = {}) {
try {
const { username } = httpRequest.params
if (!username) {
return {
statusCode: 400,
body: 'Missing username parameter.'
}
}
const user = await this.findUser.execute(username)
// ...
I have a few questions:
Should I even have controllers? Should the Router direct it to the use-case/service directly?
^^ The reason I ask that is because my controllers are really HTTP centered. For example some of them are called: PostUser, GetUser, DeleteUser. So I am guessing they should be inside the infrastructure folder, right?
I am guessing that controllers are ONLY used if your delivery mechanism is a web app, right?
You're right. There's nothing really to do with DDD because DDD is about contexts and language, but for clean architecture and ports and adapters that's the correct thought.
Normally, you would have the structure like this:
So, your application exposes an API that represents a port and you can connect different edge components that implement a physical delivery protocol of different kinds to talk to your application.
in my application I instantiate an application wide object called controller. Also I'm starting a server. Since I want to keep redundancy low, on each request I want to instantiate a frontend to controller, which is a copy/reference to controller, but with an additional pool property, which contains request wide objects/configs and can be accessed from inside controller.
var applicationPool = new ObjectPool(); // container for objects
var controller = new Controller(); // application wide instance
var server = http.createServer();
applicationPool.set("myController", controller);
server.on("request",function(req,res){
var requestPool = new ObjectPool();
requestPool.set("request",req);
requestPool.set("response",res);
/*
* pool population
* routing
* controller resolving
* parameter resolving
*/
// frontend specific to current request
var frontend = applicationPool.get("myController").create(requestPool);
// hopefully finishes res
frontend.greetAction( parameters );
/*
* post response actions
*/
}
server.listen(3000);
And the Controller class:
function Controller(){
BaseController.call(this);
// ...
}
function greetAction( parameters ){
var res = this.getObjectPool().get("response"); // defined in BaseController
res.end(format("Greetings, %s!",parameters["name"]));
}
Controller.prototype = Object.create( BaseController.prototype );
Controller.prototype.greetAction = greetAction;
Additional my thoughts about a BaseController class:
function BaseController(){ ... }
function getObjectPool(){
return this.pool;
}
function create( pool ){
var frontend = Object.create( this.__proto__, this );
frontend.pool = pool;
return frontend;
}
BaseController.prototype.getObjectPool = getObjectPool;
BaseController.prototype.create = create;
This is were I got stuck. For what I tested. If I add pool to frontend it's also applied to the controller object as well. I'm thinking about creating a new object and append all properties of controller. I'm also having a glance at proxies, having controller as target and a get trap for getObjectPool.
I know modifying res directly is bad practice. I probably will return string/buffer instead. But the described problem stays. As I plan to embed other controllers.
I'm coming from PHP+Symfony where You have a Controller class with a getContainer method and shortcuts for core objects, doing the same thing.
Any thoughts are appreciated. Awhile I'm trying to solve this.
Cheers!
Ok I think I got an solution. It's kinda tricky since I'm actually saving all "protected" data in "__" property (this.__.pool). Here is the code for the working create function in this example:
function create( pool ){
return new Proxy(this,{
get: function(target, property){
if(property === 'pool') return pool;
return target[property];
}
});
}
This returns a Proxy (frontend) for controller. Everytime I access pool of frontend, the caller will get redirected to the assigned pool argument. Even inside the frontend object.
//...
var frontend = applicationPool.get("myController").create(requestPool);
frontend.greetAction( parameters ); // this.pool will be redirected to requestPool
//...
I will wait for other suggestions, before I check in as resolved.
I started a new project from scratch with ExpressJS.
Everything works fine but now I begin to have a dozen of 'app.get(....)' function and I need to give the project a structure.
What I have in mind is quite simple, it should have a folder named 'routes' containing a file such as 'module1.js', with all of the app.get related to that module. (like I've seen in many examples)
The issue is how to tell Express to route 'http://url/module1/' to that route file and how to pass it a param variable, containing for instance the mongodb connection.
what I tried is :
var params = {
db: myMongoConnection
};
var mod1 = require('routes/module1');
app.use('/module1', mod1);
but now I still miss the 'params'.
If I try to pass it as an argument to the require method i get an error saying it needs middleware.
Another issue is related to the fact that the myMongoConnection is valid in the connection callback, so I think i need to require and use the route.js inside the MongoClient connect callback.
Any idea?
thanks a lot
For custom modules, create a folder, call it modules
In its index.js, expose the modules that you need.
Something like,
var mods = [
'mod1',
'mod2',
];
function init() {
var expose = {};
var params = {
db: myMongoConnection
};
mods.forEach(mods, function (mod) {
expose[mod] = require('./' + mod)(params);
});
return expose;
}
// export init
module.exports = init;
In mod1.js, wrap the params
module.exports = function(params) {
// all your functions here will have access to params.
}
Then in, server/app.js, require this and set it in the app.
app.set('mods', require('path-to/modules'));
Now, you can access all your modules, using app.get('mods').moduleName.methodname
I need a help in sails.js framework.i am developing the website in nodejs and sails.js framework.
is there any way to call preload action in each controller.(for ex: the controller calling time load this action).each controller having different pre load action.
Please any one suggest to me.how can i create this way or any other way.
Thanks to all.
use a service:
/service/mypre.js:
exports.first = function(req,res,cb) {
// here add you code
cb();
}
in Controller:
module.exports = {
index: function(req,res) {
sails.mypre.first(req,res, function(){
// Do other things...
});
}
}
And you may add a callback to make sure, your mypre() is done completely.
I don't know how I'd term this maybe 'static call to a koa router'? Does that seem like the right wordage here for what I'm really trying to accomplish if you were to talk about it technically?
Anyway, I'm using koa-router and I'm coding unit tests (not integration tests). So I do not want to invoke .listen() on my koa app because of that reason...it would create an http server which now makes my test an integration tests.
Instead in my test I simply want to make a straight call to the app object instance and call a route and be able to return no results and check that I returned no results in the response.
How can you do that? I can't find an example and I've tried all sorts of pseudo code attemps agains the koa app object.
If you want to test the function that koa-router routes to then just perform a unit test on that function and leave the routing out of it.
To me it sounds like you've got a file such as app.js and it contains all your code. What you can do is create a router.js file to put you route bindings and a services.js file where you can put your application logic.
So for example app.js might look like:
var koa = require("koa");
var app = module.exports = koa();
var router = require('./router.js');
app.use(router.unsecured.middleware());
app.listen(3000);
And router.js might look like:
var router = require("koa-router");
var service = require("./services.js");
var unsecured = module.exports.unsecured = new router();
unsecured.post('/account/signin', service.signinUser);
unsecured.post('/account/register', service.registerUser);
And services.js might look like:
module.exports.signinUser = function*(signinDetails) {
// contains your application signin logic
};
module.exports.registerUser = function*(registerDetails) {
// contains your application register logic
};
So in this manner you can individually test services.js. I don't see any value in individually testing router.js since it is so trivial. As #Dan Pantry shows you can test routing as part of an integration test using supertest.
Edit:
So this is a little experimental test I was playing around with to test that the routing is correct. I'm using mocha as the test runner and the code example I posted in my original code.
// standard library
var assert = require("assert");
// in app objects
var router = require('./router.js');
var service = require('./service.js');
describe("routing tests", function() {
it("test register routing, POST", function*(done) {
// arrange
var unsecured = router.unsecured;
var path = '/account/register';
var httpMethod = 'POST';
var expected = service.register.toString();
var actual;
// act
for (var i = 0; i < unsecured.stack.length; i++)
{
var pathMatch = unsecured.stack[i].path === path;
var methodMatch = unsecured.stack[i].methods.indexOf(httpMethod) >= 0;
if (pathMatch && methodMatch)
{
actual = unsecured.stack[i].middleware.toString();
break;
}
}
// assert
try {
assert.equal(expected, actual);
done();
} catch(err) {
done(err);
}
});
});
There is probably a neater way of doing this (and a more modular way for testing multiple paths) but as I said this is just a basic example to verify the routing is calling the correct service. What I'm doing is delving into the koa-router object to verify what path is bound to what service code depending on the HTTP method (e.g. POST, GET, etc).
If you have your routing and your services in modules this test completely avoids dealing with the main koa app. Although technically this test spans multiple units (the routing and the service code) so it would technically be an integration test but it does mean you don't go near app.listen() which is what you didn't want to call in your tests.