koa
Expressive middleware for node.js using generators
Koa - next generation web framework for node.js
I have multiple koa servers with a load balancer, using passport login. I would like to keep the session across all servers.
My first attempt was to set the session storage to be in mysql database, but this caused the server to call mysql on each request, thus causing performance issues.
I would like to keep the session object in the RAM of each server, and if the user gets redirected to another server by the load balancer and the server doesn't recognize the cookie, I would like it to fallback to a database and load the data into its RAM too.
Is there a way to do this?
Thanks.
Source: (StackOverflow)
I'm investigating building a web app in part with Koa, but I don't quite have a handle on the hows, whens, and whys of choosing between - and applying - the range of supportive "making async easier" technologies/approaches (listed below).
Overall the disparate guidance on the web about this subject still leaves things blurry, especially in respect to evolving best practices, or at least better ones, and under what scenarios. There seems to be little or nothing on the web that puts it all in context.
I'm hoping the responses to this big arse sprawling post can correct that. Also maybe the questions below can inspire someone to write a thorough blog post or the like to address this matter. My sense is I'm not even close to the only one who would benefit from that.
So I'd be pleased if the bright community could help answer and provide clarity to the following questions in respect to the technologies listed below (in bold type):
-- a) How, and under what circumstance (as applicable) are they complements, supplements, substitutes, and/or overlapping solutions to one another?
-- b) What are their trade-offs in respect to speed-performance, error handling ease, and debugging ease?
-- c) When, where, and why may it be better to use "this" versus "that" technology, technologies-combo, and/or approach?
-- d) Which technologies or approaches, if any, may be "dimming stars".
(Hoping that the opinions that are part of answers can be well explained.)
==============================
Technologies:
* Koa *
My understanding:
Koa is a minimal foundation for build Node apps geared for taking advantage of ECMAScript-6 features, one feature in particular being generators.
* Co *
My understanding:
-- Co is a library of utilites for running ECMAScript-6 generators (which are native to Node .011 harmony), with the goal to allieve some/much(?) of the need to write boilerplate code for running and managing generators.
-- Co is intrinsically part of Koa(?).
Specific questions:
-- If and how does one use Co differently in Koa than in a non-Koa context. In other words, does Koa wholly facade Co?
-- Could Co be replaced in Koa with some other like generator library if there is/was a better one? Are there any?
* Promise Libraries such as "Q" and Bluebird *
My understanding:
-- They are in a sense "polyfills" for implmententing the Promises/A+ spec, if and until Node natively runs that spec.
-- They have some further non-spec convenience utilities for facilitating the use promises, such as Bluebird's promisfyAll utility.
Specific questions:
-- My understanding is the ECMAScript-6 spec does/will largely reflect the Promises/A+ spec, but even so, Node 0.11v harmony does not natively implement Promises. (Is this correct?) However when it does, will technologies such as Q and Bluebird be on their way out?
-- I've read something to the effect that "Q" and Bluebird support generators. What does this mean? Does it mean in part that, for example, they to some degree provided the same utility as Co, and if so to what degree?
* Thunks and Promises *
I think I have an fair handle on what they are, but hoping someone can provide a succinct and clear "elevator pitch" definition on what each is, and of course, as asked above, to explain when to use one versus the other -- in a Koa context and not in it.
Specific questions:
-- Pro and cons to using something like Bluebird's promisfy, versus say using Thunkify (github com/visionmedia/node-thunkify)?
==============================
To give some further context to this post and its questions, it might be interesting if Koa techniques presented in the following webpages could be discussed and contrasted (especiallly on a pros vs cons basis):
-- a) www.marcusoft . net/2014/03/koaintro.html (Where's the thunks or promises, or am I not seeing something?)
-- b) strongloop . com/strongblog/node-js-express-introduction-koa-js-zone (Again, where's the thunks or promises?)
-- c) github . com/koajs/koa/blob/master/docs/guide.md (What does the "next" argument equate to, and what set it and where?)
-- d) blog.peterdecroos . com/blog/2014/01/22/javascript-generators-first-impressions (Not in a Koa context, but presents the use of Co with a promise library (Bluebird), so I'm assuming the technique/pattern presented here lends itself to usage in Koa(?). If so, then how well?
Thanks all!
Source: (StackOverflow)
Koa and Express 4.0 are both fairly new, and from what I've read, Koa was made by the Express team.
From what I understand, Koa requires features of node that are only available in 0.11 (the unstable branch) of node, and also uses generators. Express 4.0 seems to only be the next version of the Express framework.
Are there any differences I am missing completely? Is it likely (based on what the Express team has publicly stated) that Koa and Express will merge at some point in the future?
Thanks!
Source: (StackOverflow)
I know this is wrong, but essentially I want to
- connect to a db/orm via a promise
- wait on that promise to fulfill and get the models (the return from the promise)
- use the results for form a middleware generator function to place the models on the request
I suspect that this isn't the best approach, so essentially I have two questions:
- Should I be rewriting my db/orm connect to a generator function (I have a feeling that is more inline with koa style)
- Back to the original question (as I am sure I will not get a chance to rewrite all my business logic) - how do I wait on a promise to fulfill and to then return a generator function?
This is my poor attempt - which is not working, and honestly I didn't expect it to, but I wanted to start by writing code, to have something to work with to figure this out:
var connectImpl = function() {
var qPromise = q.nbind(object.method, object);
return qPromise ;
}
var domainMiddlewareImpl = function() {
let connectPromise = connectImpl()
return connectPromise.then(function(models){
return function *(next){
this.request.models = models ;
}
})
}
var app = koa()
app.use(domainMiddlewareImpl())
Source: (StackOverflow)
Seems like Bluebird overlaps Co in generator/coroutine related functionality. Bluebird is espoused to have exceptional speed-performance, so for discussion sake, (assuming the aforementioned overlap premise is true) if one wanted to substitute Bluebird for Co in Koa (Node.js context), could it be easily be done without diminishing Koa's functionality, and if so how?
(My guess is it can't practically be done since it seems Koa is built over Co and doesn't explicitly expose it, but facades it. Such a substitution it seems would be tantamount to replacing jQuery with something else in Bootstrap)
Source: (StackOverflow)
I have existing code which implements an express middleware. How can I use this middleware in a Koa application?
When I try to call app.use(expressMiddleware)
in order to use the middleware in my Koa app, Koa complains that a generator function is required:
AssertionError: app.use() requires a generator function
So I guess that some kind of adapter or trick is needed here... ideas?
Source: (StackOverflow)
I have created a login which is able to login a user and store the user if they are new in the database.
The user is then redirected to /
and then is checked if they are authenticated or not, see below (app.js):
.get('/', function* () {
if (this.isAuthenticated()) {
yield this.render('homeSecure', {}); // <-- need user data here
} else {
yield this.render('homePublic', {});
}
As I commented in the code, I would like to send the user object of which is logged in. I have no idea how to get a hold of the id of the person logged in as the documentation for koa in general is not as complete as that of express.
I am using koa-generic-session-mongo
to handle my sessions. Here is my GoogleStrategy (auth.js):
var user = null;
// ...
var GoogleStrategy = require('passport-google').Strategy;
passport.use(new GoogleStrategy({
returnURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/google/callback',
realm: 'http://localhost:' + (process.env.PORT || 3000)
},
function (identifier, profile, done) {
var emails = new Array();
for (var i = 0; i < profile.emails.length; i++) {
emails.push(profile.emails[i].value);
}
co(function* () {
yield users.findOne({
emails: emails
});
});
if (user === null) { // first time signin, create account
co(function* () {
user = {
id: 1,
name: profile.displayName,
emails: emails
};
yield users.insert(user);
});
}
console.log(user);
done(null, user);
}));
Source: (StackOverflow)
I recently created my own module for node.js for use with the koa module. It's a translation module like koa-i18n. I've studied other koa modules to see how functions/properties are applied to the koa context/request and some of them use the Object.defineProperty function, but what I did in my module was apply a function directly on 'this'.
So, what is the difference between using
Object.defineProperty(app.context, 'getSomeValue', { ... });
and
return function* (next) { this.getSomeValue = function () { ... } }
I've also come across the node-delegates module which uses the 'apply' function.
Which of these methods is the preferred way of applying a function/property to an existing object and what are the pros and cons?
Source: (StackOverflow)
I would like use the WebPack to compile server-side scripts which contain the Harmony (ES6) generators. I would like to keep them and not use any kind of polyfills or transpilers. But the WebPack complains about a missing loader. Does WebPack support to compile a straight forward generator please?
Stack:
io.js
webpack
koa framework
Source: (StackOverflow)
When a request comes in, I want to reload the controller to improve debugging speed.
When I make a change to a controller method I have to reload the whole server which take 4-5 seconds.
I am also using koa-mount
to configure different endpoints so the solution must be compatible with koa-mount
.
Source: (StackOverflow)
I'm trying to get Koa to isomorphically render a html string it receives from react-router.
Here's the code I've been trying to make work:
server.js
import koa from 'koa';
import React from "react";
import Router from "react-router";
import routes from "./routes";
const server = koa();
const port = process.env.NODE_ENV || 8000;
server.use(function *() {
try {
yield Router.run(routes, this.request.url, function (Handler) {
var content = React.renderToString(<Handler/>)
this.body = content
})
}
catch (err) {
this.status = err.status || 500;
this.body = err.message;
this.app.emit('error', err, this);
}
})
server.listen(port, function(err) {
if (err) throw err;
console.log("Server running on: http://localhost:"+port)
})
routes.js
import React from "react"
import {Route, DefaultRoute} from "react-router"
import Main from "./components/main"
export default (
<Route path="/">
<DefaultRoute handler={Main} name="main" />
</Route>
)
main.js
import React from "react"
const Main = React.createFactory(React.createClass ({
render () {
return (
<div>HELLO</div>
)
}
}))
export default Main
Getting several errors:
Warning: Component(...): No render
method found on the returned
component instance: you may have forgotten to define render
in your
component or you may have accidentally tried to render an element
whose type is a function that isn't a React component.
Warning: Don't set the props property of the React element. Instead,
specify the correct value when initially creating the element.
TypeError: Can't add property context, object is not extensible
Warning: Something is calling a React component directly. Use a
factory or JSX instead. See: https://fb.me/react-legacyfactory
Source: (StackOverflow)
Currently, WebStorm reports that KoaJS's methods are undefined. It's a minor, yet persistent annoyance. I've searched on the net and I've searched through WebStorm's configuration dialogs to no avail.
Does anyone use WebStorm with KoaJS and have intellisense/code completion working properly?
Source: (StackOverflow)
This question already has an answer here:
I came across this operator preceding a 'this' keyword in some Node.js Harmony code, specifically working with the Koa web framework.
The example code is below:
app.use(function *(){
var n = ~~this.cookies.get('view') + 1;
this.cookies.set('view', n);
this.body = n + ' views';
});
A routine google search showed up nothing so I am throughly confused. The only thing I can say for certain is that it is essential to the functionality of that snippet, as the code stops working when it is removed.
Any insight would be appreciated with identifying the purpose of this alien operator.
Source: (StackOverflow)
Trying to fire off mutiple requests off to the beats api using bluebird as well as koa for generators.
After reading some documentation I figured the following would work
var request = require('co-request'),
_ = require('lodash'),
Promise = require('bluebird');
request = Promise.promisifyAll(request);
module.exports.getTracks = function *tracks(){
firstCall = yield makeAPICall('users/' + me + '/mymusic/tracks?limit=150');
total = firstCall.body.info.total;
total -= 150;
tracks = firstCall.body.data;
//Beats only allows a maximum of 150 tracks per call
//If more tracks are needed then the remainder is called in sets of 150
var offset = 150;
while (total > 0) {
promises.push(makeAPICall('users/' + me + '/mymusic/tracks?limit=150&offset=' + offset));
offset += 150;
total -= 150;
}
var responses = yield(Promise.all(promises));
}
function makeAPICall (query){
var authOptions = {
url: 'https://partner.api.beatsmusic.com/v1/api/' + query,
headers: { 'Authorization': 'Bearer ' + accessToken },
json: true
};
return request.get(authOptions);
}
The method makeAPI call works as expected used with firstCall, but for some reason when I start placing the makeAPICall method into the array they never seem to execute. The variable responses yields out just an array of functions instead of an array of responses from the beats api. What do I need to change to make responses return an array of objects similar to that of firstCall?
Source: (StackOverflow)
I'm somewhat new to node, and I'm completely new to koa. I'm trying to use generators to do async web requests to an API, but I can't figure out how to put all the pieces together.
As a note, I'm using bluebird because I saw some examples do that, and it seemed like a good idea. If there's an easier way to do what I want without bluebird, that's totally fine as well.
In my module:
plugin.searchForItem = function * (name) {
Promise = require('bluebird');
request = Promise.promisifyAll(require('request'));
console.log("making request");
yield request.getAsync('http://apisitegoeshere.com/apicall').then(function * (result) {
var response = result[0];
var body = result[1];
console.log(response.statusCode);
yield response;
});
};
and I'm calling it like this:
search.searchForShow = function (name) {
data = this.plugins[0].searchForItem(name);
console.log("search returned: " + data);
console.log("search returned2: " + JSON.stringify(data.next()));
console.log("search returned3: " + JSON.stringify(data.next()));
return data;
};
When I look in my console, I see:
search returned: [object Generator]
making request
search returned2: {"value":{"isFulfilled":false,"isRejected":false},"done":false}
search returned3: {"done":true}
I know my code is kind of all over the place, but I've worked on it for hours and I'm still no closer to fixing it.
Thanks!
Source: (StackOverflow)