Looking for both live and dummy projects that have used ES6 generators.
Hello
For what it's worth, I found using generators in Koa such a pleasure to get some easy to read and easy to maintain code .
Sample code (quickly edited to make it more generic rather than our real names, hopefully I haven't introduced any typos, the idea is to have a basic service that serve as a proxy to ElasticSearch, slightly modified here to only show the cascade of generators function* / yield)
In the server.ts file:
import {service1} from './controllers/service1/controllers';
router.get(`${config.routeService1}*`, service1.endpointService1);
In the controllers/service1/controllers.ts file, I define the generators
export namespace service1 {
export function* endpointService1() {
// Here I only digest the arguments and format the response , like a public-facing API for the module
var args: IService1RequestArgs = {
originalUrl: this.originalUrl,
body: this.request.body,
queryString: this.query
};
var myResponse: IService1RequestResult = yield forwardSearch(args);
this.request.ctx.state.service1Logs = myResponse.logs; // the ctx.state is consumed by middleware added to the server for logs, formatting, profiling, ...
this.body = myResponse.body;
}
export function* forwardSearch(searchArgs: IService1RequestArgs) {
// Read the search query
const searchString: string = searchArgs.queryString.q;
const localRoute = `${config.routePrefix}${config.routeSearch}`;
const targetUrl: string = searchArgs.originalUrl.replace(localRoute, '');
// Send this to Elasticsearch
const options = {
headers: {
'User-Agent': `${config.userAgent}`,
'Authorization': `${config.esAuth}`
},
url: `${config.esSearchEndpoint}${targetUrl}`,
method: 'POST',
qs: searchArgs.queryString,
json: true,
body: searchArgs.body
};
// And forward the response
const kresponse = yield krequest(options);
const results: IESResponse = <IESResponse>kresponse.body;
// If the response is valid, read some info to report the results
const logs: ISearchLog = myLogger.getBasicLogProps();
// Here add other properties about what you want to debug/profile/log, ...
return {
body: results,
logs: logs
};
}
}
In other services, one request triggers a cascade of calls (get result from a service A, then send a result from A to B, and send back a response composed from the combination of A and B. Using generators and yield makes it very easy to read and handle.
Ovidiu Bădiță
You may like this one: medium.com/javascript-scene/7-surprising-things-i…