SlideShare a Scribd company logo
Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded.
From world
to
The task:
Backend for real-time
communication app
Why Ruby?
2011
Elegant language &
environment
1. Beautiful Language: Dynamic, OO, linear
##
# Distribute a system message
#
def find_and_distribute(message_id)
message = Message.find(message_id)
raise SystemError, "Message not found" if message.nil?
message.start_distribution
return message.to_json
rescue SystemError
log.error "[API] distribute fail: "#{e.message}”
end
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
Elegant language &
environment
class MediaRobotUser
include Mongoid::Document
# schema
field :rss_url, type: String
field :updated, type: DateTime
field :update_freq, type: Integer, default: 5
# Validations
validates :rss_url, :presence => true
validates :update_freq, :presence => true
def activate_user
robot_queue = ”robot_update_#{self.id.to_s}"
Resque.remove_schedule(robot_queue)
schedule_options =
{ 'every' => '15m',
'custom_job_class' => “Bot::Jobs::UpdateMediaRobot",
'queue' => :update_media_robot,
'args' => self.id.to_s,
}
Resque.set_schedule(robot_queue, schedule_options)
end
end # class MediaRobotUser
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
3. Robust libraries: Community focus on libs selected for Rails
Elegant language &
environment
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
3. Robust libraries: Rails gives focus on library development
4. Killer server stack for API: Thin + Rack + Sinatra
Elegant language &
environment
Dedicated async web server for Ruby apps
Instead of complex Apache/Passenger setup, you
download thin and just run your app with it.
Layer between web servers and web frameworks
De facto standard in Ruby world: choose any ruby
web server, choose any ruby framework, throw
own middleware into soup and it just works!
Simple HTTP request handler on top of Rack
No MVC bloat for a simple, RESTful API
application, but want still use same robust libraries
Rails apps use. Just write functionality for your
GET /my/api endpoint and go!
# Set Rails session to OAuth2 access token convert middleware
use Auth::RailsSessionConverter
# Set OAuth2 handler
use Rack::OAuth2::Server
# launch Sinatra REST API server
require File.dirname(__FILE__) + '/app/access/restapi'
map('/rest/vp5/') { run Access::RESTAPI }
2. Define Rack configuration (e.g. myrack.ru):
3. Run web server:
1. Write Sinatra web app:
##
# API call to get backend version.
#
get '/system/version' do
authenticate!('int_api_user')
content_type :json
status 200
return (JSON :data_api_version => 'proto v5.0')
end
$ bundle exec thin –R myrack.ru –p 9400 -e development start
Ruby ≠ Rails! Sinatra,
Resque and many other
cool frameworks
Could map
other apps to
different paths
“homemade”
middleware block
hooked in!
No fuzz
The next task:
Backend for Media App
2013
So.. Let’s think about
Culture for
unsecure
code?
Born in
2011 – are
the libs
there?
Don’t want
that callback
spaghetti!
DB drivers
and
ODMs?Performance
?
How to keep
running in
production?
/**
* Static content delivery
*/
staticDelivery: function (req, res) {
var tmpDir = lzconf.filedbdir + "/tmp";
file.mkdir(tmpDir, '777’, function() {
var fileSource = lzconf.filedbdir + "/" + req.params[0];
// do the work
easyimg.rescrop(options, function(err, image) {
console.log('Resized and cropped: ', image);
// send file
res.sendfile(tmpTarget, {maxAge: 604800}, function(err) {
if (err) { … }
// remove temp file
fs.unlink(tmpTarget, function(err, success) {
…
});
});
});
});
}
function myApiFunc(callback)
{
/*
* This pattern does NOT work!
*/
try {
doSomeAsynchronousOperation(function (err) {
if (err)
throw (err);
/* continue as normal */
});
} catch (ex) {
callback(ex);
}
}
Source: http://www.joyent.com/developers/node/design/errors
Whaaat?
Cannot use
try…catch??
“Sadly, that seems to be the story of
Node.JS and the frameworks that use it.
Derby, Meteor, SocketStream– they all are
relatively new and immature, and in some
cases, lack critical functionality of a web
framework or have serious issues with
security. That sort of puts me, as a
developer, in an odd position. I’ve
determined Node.JS is a good platform for a
project, but without reinventing the wheel,
what framework do I use to speed up
development?”
– Andrew Munsell
https://www.andrewmunsell.com/blog/the-odd-
state-of-nodejs-and-its-frameworks
“Sinatra inspired web development
framework for node.js – insanely fast,
flexible, and simple.”
Yes!
Powered by Connect
More over,
future looked
promising:
“Next generation web framework
for node js.”
Why it rocks
ECMAScript 6: Generators
$ node --harmony
> function* giveMeFruit() {
... yield "apple";
... yield "banana";
... }
> var fruitMachine = giveMeFruit()
> fruitMachine.next()
{ value: 'apple', done: false }
> fruitMachine.next()
{ value: 'banana', done: false }
> fruitMachine.next()
{ value: undefined, done: true }
> fruitMachine.next()
Error: Generator has already finished
at GeneratorFunctionPrototype.next (native)
…
What an earth
this has to do
with a HTTP
framework?
Why it rocks
co– “The ultimate generator based flow-
control goodness for nodejs (supports thunks,
promises, etc)”
var co = require('co');
co(function *(){
console.log(“updating user...”);
try {
var user = yield Users.findOneById(‘123’).exec();
if (!user) throw new Error(“Cannot find user”);
user.name = “juha”;
yield Promise.promisify(user.save, user)();
} catch (err) {
console.log(“Name update failed: ”, err);
}
})()
This Mongoose
finder returns a
promise by default
“Save” need to be
transferred into
promise first for
yield
Try…catch as it
should be 
Generator flow control (co)
is the heart of Koa server
Why it rocks
var koa = require('koa’)
, api = require('./v1/myApiModule’), ...
app.use(mount(‘/api/v1’, api));
app.listen(8080);
Why it rocks
Additional middleware to
handle routing, e.g. koa-
mount
Custom middleware
upstream &
downstream
app.use(function *(next) {
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
Many needed middleware
libs already ported, such as
* koa-session-mongo
* koa-passport
* koa-cors
* koa-send
app.use(session());
app.use(passport.username());
app.use(function *(next) {
try {
yield next;
} catch (err) {
this.status = err.status || 500;
}
})
More robust code
API
with koa-router
Why it rocks
var Router = require('koa-router')
var API = new Router()
API.get('/topics/:topicId', function *() {
try {
this.body = yield MySubSystem.getTopic({
id: this.params.topicId,
filter: this.request.query.filter_by
});
} catch (err) {
if (err.name === "DocumentNotFoundError") {
this.body = "Topic not found";
this.status = 404;
} else {
throw err;
}
}
}
Why it rocks
Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded.
Thank you!

More Related Content

What's hot

Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
Arnout Kazemier
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
LaunchAny
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
Almog Baku
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
Antonio Peric-Mazar
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
Shengyou Fan
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
Yusuke Wada
 
Md+wiki
Md+wikiMd+wiki
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
Andrea Tarquini
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
Aaron Stannard
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframework
Inviqa
 
Express node js
Express node jsExpress node js
Express node js
Yashprit Singh
 
Socket.io
Socket.ioSocket.io
Socket.io
Antonio Terreno
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
John Dave Decano
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
Anatoly Sharifulin
 

What's hot (20)

Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 
Md+wiki
Md+wikiMd+wiki
Md+wiki
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Express js
Express jsExpress js
Express js
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframework
 
Express node js
Express node jsExpress node js
Express node js
 
Socket.io
Socket.ioSocket.io
Socket.io
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 

Similar to From Ruby to Node.js

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Proposal
ProposalProposal
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
Edureka!
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
Edureka!
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easy
Ulrich Krause
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0
Thomas Chacko
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
Tatsuhiko Miyagawa
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
Ben Hall
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React Native
Ian Wang
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
Diacode
 

Similar to From Ruby to Node.js (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Proposal
ProposalProposal
Proposal
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easy
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React Native
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 

Recently uploaded

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 

Recently uploaded (20)

Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 

From Ruby to Node.js

  • 1. Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded. From world to
  • 2. The task: Backend for real-time communication app
  • 5. Elegant language & environment 1. Beautiful Language: Dynamic, OO, linear
  • 6. ## # Distribute a system message # def find_and_distribute(message_id) message = Message.find(message_id) raise SystemError, "Message not found" if message.nil? message.start_distribution return message.to_json rescue SystemError log.error "[API] distribute fail: "#{e.message}” end
  • 7. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid Elegant language & environment
  • 8. class MediaRobotUser include Mongoid::Document # schema field :rss_url, type: String field :updated, type: DateTime field :update_freq, type: Integer, default: 5 # Validations validates :rss_url, :presence => true validates :update_freq, :presence => true def activate_user robot_queue = ”robot_update_#{self.id.to_s}" Resque.remove_schedule(robot_queue) schedule_options = { 'every' => '15m', 'custom_job_class' => “Bot::Jobs::UpdateMediaRobot", 'queue' => :update_media_robot, 'args' => self.id.to_s, } Resque.set_schedule(robot_queue, schedule_options) end end # class MediaRobotUser
  • 9. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid 3. Robust libraries: Community focus on libs selected for Rails Elegant language & environment
  • 10.
  • 11. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid 3. Robust libraries: Rails gives focus on library development 4. Killer server stack for API: Thin + Rack + Sinatra Elegant language & environment
  • 12. Dedicated async web server for Ruby apps Instead of complex Apache/Passenger setup, you download thin and just run your app with it. Layer between web servers and web frameworks De facto standard in Ruby world: choose any ruby web server, choose any ruby framework, throw own middleware into soup and it just works! Simple HTTP request handler on top of Rack No MVC bloat for a simple, RESTful API application, but want still use same robust libraries Rails apps use. Just write functionality for your GET /my/api endpoint and go!
  • 13. # Set Rails session to OAuth2 access token convert middleware use Auth::RailsSessionConverter # Set OAuth2 handler use Rack::OAuth2::Server # launch Sinatra REST API server require File.dirname(__FILE__) + '/app/access/restapi' map('/rest/vp5/') { run Access::RESTAPI } 2. Define Rack configuration (e.g. myrack.ru): 3. Run web server: 1. Write Sinatra web app: ## # API call to get backend version. # get '/system/version' do authenticate!('int_api_user') content_type :json status 200 return (JSON :data_api_version => 'proto v5.0') end $ bundle exec thin –R myrack.ru –p 9400 -e development start Ruby ≠ Rails! Sinatra, Resque and many other cool frameworks Could map other apps to different paths “homemade” middleware block hooked in! No fuzz
  • 14. The next task: Backend for Media App
  • 15. 2013
  • 16. So.. Let’s think about Culture for unsecure code? Born in 2011 – are the libs there? Don’t want that callback spaghetti! DB drivers and ODMs?Performance ? How to keep running in production?
  • 17. /** * Static content delivery */ staticDelivery: function (req, res) { var tmpDir = lzconf.filedbdir + "/tmp"; file.mkdir(tmpDir, '777’, function() { var fileSource = lzconf.filedbdir + "/" + req.params[0]; // do the work easyimg.rescrop(options, function(err, image) { console.log('Resized and cropped: ', image); // send file res.sendfile(tmpTarget, {maxAge: 604800}, function(err) { if (err) { … } // remove temp file fs.unlink(tmpTarget, function(err, success) { … }); }); }); }); }
  • 18. function myApiFunc(callback) { /* * This pattern does NOT work! */ try { doSomeAsynchronousOperation(function (err) { if (err) throw (err); /* continue as normal */ }); } catch (ex) { callback(ex); } } Source: http://www.joyent.com/developers/node/design/errors Whaaat? Cannot use try…catch??
  • 19. “Sadly, that seems to be the story of Node.JS and the frameworks that use it. Derby, Meteor, SocketStream– they all are relatively new and immature, and in some cases, lack critical functionality of a web framework or have serious issues with security. That sort of puts me, as a developer, in an odd position. I’ve determined Node.JS is a good platform for a project, but without reinventing the wheel, what framework do I use to speed up development?” – Andrew Munsell https://www.andrewmunsell.com/blog/the-odd- state-of-nodejs-and-its-frameworks
  • 20.
  • 21. “Sinatra inspired web development framework for node.js – insanely fast, flexible, and simple.” Yes! Powered by Connect
  • 23. “Next generation web framework for node js.”
  • 24. Why it rocks ECMAScript 6: Generators $ node --harmony > function* giveMeFruit() { ... yield "apple"; ... yield "banana"; ... } > var fruitMachine = giveMeFruit() > fruitMachine.next() { value: 'apple', done: false } > fruitMachine.next() { value: 'banana', done: false } > fruitMachine.next() { value: undefined, done: true } > fruitMachine.next() Error: Generator has already finished at GeneratorFunctionPrototype.next (native) … What an earth this has to do with a HTTP framework?
  • 25. Why it rocks co– “The ultimate generator based flow- control goodness for nodejs (supports thunks, promises, etc)” var co = require('co'); co(function *(){ console.log(“updating user...”); try { var user = yield Users.findOneById(‘123’).exec(); if (!user) throw new Error(“Cannot find user”); user.name = “juha”; yield Promise.promisify(user.save, user)(); } catch (err) { console.log(“Name update failed: ”, err); } })() This Mongoose finder returns a promise by default “Save” need to be transferred into promise first for yield Try…catch as it should be 
  • 26. Generator flow control (co) is the heart of Koa server Why it rocks
  • 27. var koa = require('koa’) , api = require('./v1/myApiModule’), ... app.use(mount(‘/api/v1’, api)); app.listen(8080); Why it rocks Additional middleware to handle routing, e.g. koa- mount Custom middleware upstream & downstream app.use(function *(next) { var start = new Date; yield next; var ms = new Date - start; this.set('X-Response-Time', ms + 'ms'); }); Many needed middleware libs already ported, such as * koa-session-mongo * koa-passport * koa-cors * koa-send app.use(session()); app.use(passport.username()); app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; } }) More robust code
  • 29. var Router = require('koa-router') var API = new Router() API.get('/topics/:topicId', function *() { try { this.body = yield MySubSystem.getTopic({ id: this.params.topicId, filter: this.request.query.filter_by }); } catch (err) { if (err.name === "DocumentNotFoundError") { this.body = "Topic not found"; this.status = 404; } else { throw err; } } } Why it rocks
  • 30.
  • 31.
  • 32. Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded. Thank you!

Editor's Notes

  1. From Ruby world to Node.js
  2. CMSs are not for realtime system Java felt more for enterprise level solution PHP language felt outdated and did not found suitable stack Rails MVC felt too heavy for API server purpose Pure Ruby with dedicated servers and framework was the choice
  3. Javascript famous for silently ignoring problems. Initially people did not handle CSRF. Sometimes neglected exception catching. Quickly written libs. No use of reverse proxy for caching and load balancing is needed.