Created
August 13, 2012 12:20
-
-
Save jsmarkus/3340123 to your computer and use it in GitHub Desktop.
Command line YQL google searcher on FSM pattern. Test of npm module "automata".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var automata = require('automata') | |
, yql = require('yql') | |
, readline = require('readline') | |
; | |
automata.registerFSM({ | |
name : "Test", | |
logic : TestLogic, | |
state : [ | |
{ name : 'idle', onEnter : 'idle', initial : true }, | |
{ name : 'read', onEnter : 'read' }, | |
{ name : 'fetch', onEnter : 'fetch' }, | |
{ name : 'render', onEnter : 'render' }, | |
], | |
transition : [ | |
{ event : 'run', from : 'idle', to : 'read' }, | |
{ event : 'userrequest', from : 'read', to : 'fetch', onPostGuard : 'userrequest_postGuard' }, | |
{ event : 'fetched', from : 'fetch', to : 'render' }, | |
{ event : 'rendered', from : 'render', to : 'read' }, | |
{ event : 'error', from : 'fetch', to : 'read' }, | |
] | |
}); | |
function TestLogic () { | |
this.reader = readline.createInterface(process.stdin, process.stdout); | |
} | |
TestLogic.prototype.idle = function (session, state, transition, msg) { | |
} | |
TestLogic.prototype.read = function (session, state, transition, msg) { | |
this.reader.question('Search: ', function (answer) { | |
session.dispatch({msgId : 'userrequest', input:answer}); | |
}); | |
} | |
TestLogic.prototype.fetch = function (session, state, transition, msg) { | |
yql.exec('select titleNoFormatting from google.search where q = @keywords', function (res) { | |
if(res.query.results) { | |
session.dispatch({ msgId:'fetched', data : res.query.results }); | |
} else { | |
session.dispatch({ msgId:'error'}); | |
} | |
}, {keywords: msg.input}); | |
} | |
TestLogic.prototype.render = function (session, state, transition, msg) { | |
var i | |
, results = msg.data.results | |
; | |
for(i = 0; i < results.length; i++) { | |
console.log(results[i].titleNoFormatting); | |
} | |
session.dispatch({ msgId:'rendered'}); | |
} | |
TestLogic.prototype.userrequest_postGuard = function (session, state, transition, msg) { | |
if(msg.input === '') { | |
throw 'Empty message'; | |
} | |
} | |
var session = automata.createSession('Test'); | |
var logic = session.logic; | |
session.dispatch({msgId: 'run'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment