SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Entities on Node.jsEntities on Node.js
/thanpolas/entity/thanpolas/entity
Entities useEntities use
CIP
​for Classical Inheritance
/thanpolas/cip
Bluebird
for the 100% Promises API
/petkaantonov/bluebird
Middlewarify
for creating middleware
/thanpolas/middlewarify
Entities extendEntities extend
events.EventEmitter
...and that's the only thing they do
Creating an EntityCreating an Entity
var entity = require('entity');
var EntityChild = entity.extend(function() {
this.a = 1;
});
var EntityGrandChild = EntityChild.extend();
entity.extend
var entity = require('entity');
var UserEntity = entity.extendSingleton(function() {});
/* ... */
var userEnt = UserEntity.getInstance();
entity.extendSingleton
Entities AdaptorsEntities Adaptors
MongooseMongoose
MongoDB ORM
http://mongoosejs.com/
SequelizeSequelize
PostgreSQL
MySQL
MariaDB
SQLite
http://sequelizejs.com/
CRUD PrimitivesCRUD Primitives
create(data)
read(query=)
readOne(query)
readLimit(?query, offset, limit)
update(query, updateValues)
delete(query)
count(query=)
CRUD PrimitivesCRUD Primitives
create()create()
entity.create({name: 'thanasis'})
.then(function(udo) {
udo.name === 'thanasis'; // true
})
.catch(function(error) {
// deal with error.
});
... so on and so forth ...
Entity HooksEntity Hooks
Middlewarify in action
before
after
last
Entity HooksEntity Hooks
beforebefore
// a middleware with synchronous resolution
entity.read.before(function(data){
if (!data.name) {
throw new TypeError('No go my friend');
}
});
// then...
entity.read({}).then(function(document) {
// you'll never get here
}, function(err) {
err instanceof Error; // true
err.message === 'No go my friend'; // true
});
Hooks are FiFoHooks are FiFo
Order MATTERSOrder MATTERS
Hooks areHooks are
MiddlewareMiddleware
Before HooksBefore Hooks
Get the exact same number or arguments
After & Last HooksAfter & Last Hooks
Gets the result plus the original number or arguments
Entity HooksEntity Hooks
AsynchronicityAsynchronicity
entity.create.before(function(data){
return promiseReturningFn(function(result) {
resolve(result + 1);
});
});
Extending EntitiesExtending Entities
adding new methodsadding new methods
Extending EntitiesExtending Entities
Just use the prototypeJust use the prototype
var Entity = require('entity');
var UserEntity = module.exports = Entity.extend();
UserEntity.prototype.report = function(userId) {
return promiseReturningAction(userId);
};
Extending EntitiesExtending Entities
Using method()Using method()
var Entity = require('entity');
var UserEntity = module.exports = Entity.extend(function() {
this.method('report', this._report.bind(this));
this.report.before(this._checkUserId.bind(this));
this.report.after(this._normalize.bind(this));
});
UserEntity.prototype._report = function(userId) {
return promiseReturningAction(userId);
};
Let's combine all upLet's combine all up
var ClipEntity = module.exports = EntityBase.extendSingleton(function() {
this.setModel(clipModel.Model);
this.method('readOneApi', this.readOne);
this.method('readLimitApi', this.readLimit);
this.method('updateApi', this.update);
this.method('readApi', this.read);
// Apply system wide (global) filters
this.readLimitApi.before(this.systemFilter.bind(this));
this.readOneApi.before(this.systemFilter.bind(this));
// Clip Creation middleware
this.create.before(this._populateActiveEvent.bind(this));
this.create.after(this._processNewClip.bind(this));
// Record sanitization middleware
this.updateApi.after(helpers.skipArgs(this.sanitizeResult, 2, this));
this.readLimitApi.after(helpers.skipArgs(this.sanitizeResults, 3, this));
this.readOneApi.after(helpers.skipArgs(this.sanitizeResult, 1, this));
});
A Production-ish EntityA Production-ish Entity
Entity Hands OnEntity Hands On
this.readLimitApi.before(this.systemFilter.bind(this));
/**
* Apply system filters in all incoming READ queries
* to exclude deleted and corrupt items.
*
* @param {Object} query The query.
*/
ClipEntity.prototype.systemFilter = function(query) {
query.notFound = { ne: true };
query.processed = true;
};
Entity Hands OnEntity Hands On
this.create.after(this._processNewClip.bind(this));
/**
* Post creation clip processing.
*
* @param {Object} data Item used to create the record.
* @param {app.entity.ClipProcess} processEnt The process entity.
* @param {mongoose.Document} clipItem The result.
* @return {Promise} A promise.
* @private
*/
ClipEntity.prototype._processNewClip = Promise.method(function(data, processEnt,
clipItem) {
processEnt.clipId = clipItem.id;
log.finest('_processNewClip() :: Clip Saved to DB, starting FS save...', clipItem.id);
return this._checkWatermarkAndStore(processEnt, clipItem)
.bind(processEnt)
.then(processEnt.createThumbnail)
.then(processEnt.checkS3)
.then(processEnt.updateDatabase)
.then(function() {
log.fine('_processNewClip() :: Clip processing finished:',
processEnt.sourceFilePath);
})
.catch(processEnt.moveToTrash)
.catch(processEnt._deleteRecord);
});
Now let's get crazyNow let's get crazy
EntitiesEntities
++
CrudeCrude
POST /user
GET /user
GET /user/:id
PUT /user/:id
PATCH /user/:id
DELETE /user/:id
/thanpolas/crude
... but not today... but not today
Thank you
(here is where you applaud)
Thanasis Polychronakis
@thanpolas
http://www.slideshare.net/thanpolas
Questions?
Be a critic
Thanasis Polychronakis
@thanpolas
http://www.slideshare.net/thanpolas
Shameless Plug Time
Promo Code
bgwebsummit
From 60€ --> 40€
15/5/2015
@ Thessaloniki Greece
devitconf.org
Questions?
Thanasis Polychronakis
@thanpolas

Contenu connexe

Tendances

Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...VMware Tanzu
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6Julien CROUZET
 
Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Eric Bourdet
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
HTTP and Your Angry Dog
HTTP and Your Angry DogHTTP and Your Angry Dog
HTTP and Your Angry DogRoss Tuck
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesNATS
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowPrabhdeep Singh
 
Hexagonal architecture: how, why and when
Hexagonal architecture: how, why and whenHexagonal architecture: how, why and when
Hexagonal architecture: how, why and whenXoubaman
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 

Tendances (20)

Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6
 
Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
HTTP and Your Angry Dog
HTTP and Your Angry DogHTTP and Your Angry Dog
HTTP and Your Angry Dog
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
MERN PPT
MERN PPTMERN PPT
MERN PPT
 
NestJS
NestJSNestJS
NestJS
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices Architectures
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
Hexagonal architecture: how, why and when
Hexagonal architecture: how, why and whenHexagonal architecture: how, why and when
Hexagonal architecture: how, why and when
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 

En vedette

Business considerations for node.js applications
Business considerations for node.js applicationsBusiness considerations for node.js applications
Business considerations for node.js applicationsAspenware
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Tesi pozzani elena
Tesi pozzani elenaTesi pozzani elena
Tesi pozzani elenaimartini
 
The Evaluation of Time Performance in the Emergency Response Center in Kerman...
The Evaluation of Time Performance in the Emergency Response Center in Kerman...The Evaluation of Time Performance in the Emergency Response Center in Kerman...
The Evaluation of Time Performance in the Emergency Response Center in Kerman...Emergency Live
 
Presentasi Komunitas S3-System Team 007
Presentasi Komunitas S3-System Team 007Presentasi Komunitas S3-System Team 007
Presentasi Komunitas S3-System Team 007profithunter007
 
It asset management_wp
It asset management_wpIt asset management_wp
It asset management_wpwardell henley
 
Ufeed estrategia de marketing responsable (1)
Ufeed estrategia de marketing responsable (1)Ufeed estrategia de marketing responsable (1)
Ufeed estrategia de marketing responsable (1)Kasia Goździkowska
 
Lectura 2 robo en-el-almacen-de-juguetes
Lectura 2 robo en-el-almacen-de-juguetesLectura 2 robo en-el-almacen-de-juguetes
Lectura 2 robo en-el-almacen-de-juguetesJunta de Extremadura
 
First Euro Case Study
First Euro Case StudyFirst Euro Case Study
First Euro Case Studyajithsrc
 
Nomadic Brochure sje 2013
Nomadic Brochure sje 2013Nomadic Brochure sje 2013
Nomadic Brochure sje 2013Greg Sinclair
 
Nuevo documento de microsoft word
Nuevo documento de microsoft wordNuevo documento de microsoft word
Nuevo documento de microsoft wordmaribel allen
 
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】満徳 関
 
Mi credo pedagógico. J.D
Mi credo pedagógico. J.DMi credo pedagógico. J.D
Mi credo pedagógico. J.Ddeboratm
 

En vedette (20)

Intro to node.js web apps
Intro to node.js web appsIntro to node.js web apps
Intro to node.js web apps
 
Intro to node.js
Intro to node.jsIntro to node.js
Intro to node.js
 
HowTo Freelance
HowTo FreelanceHowTo Freelance
HowTo Freelance
 
Entities, the theory
Entities, the theoryEntities, the theory
Entities, the theory
 
Business considerations for node.js applications
Business considerations for node.js applicationsBusiness considerations for node.js applications
Business considerations for node.js applications
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Tesi pozzani elena
Tesi pozzani elenaTesi pozzani elena
Tesi pozzani elena
 
The Evaluation of Time Performance in the Emergency Response Center in Kerman...
The Evaluation of Time Performance in the Emergency Response Center in Kerman...The Evaluation of Time Performance in the Emergency Response Center in Kerman...
The Evaluation of Time Performance in the Emergency Response Center in Kerman...
 
Presentasi Komunitas S3-System Team 007
Presentasi Komunitas S3-System Team 007Presentasi Komunitas S3-System Team 007
Presentasi Komunitas S3-System Team 007
 
It asset management_wp
It asset management_wpIt asset management_wp
It asset management_wp
 
Ufeed estrategia de marketing responsable (1)
Ufeed estrategia de marketing responsable (1)Ufeed estrategia de marketing responsable (1)
Ufeed estrategia de marketing responsable (1)
 
COMPASS1
COMPASS1COMPASS1
COMPASS1
 
Lectura 2 robo en-el-almacen-de-juguetes
Lectura 2 robo en-el-almacen-de-juguetesLectura 2 robo en-el-almacen-de-juguetes
Lectura 2 robo en-el-almacen-de-juguetes
 
First Euro Case Study
First Euro Case StudyFirst Euro Case Study
First Euro Case Study
 
Nomadic Brochure sje 2013
Nomadic Brochure sje 2013Nomadic Brochure sje 2013
Nomadic Brochure sje 2013
 
Nuevo documento de microsoft word
Nuevo documento de microsoft wordNuevo documento de microsoft word
Nuevo documento de microsoft word
 
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】
POStudy塾 ~プロダクトオーナーシップをテーマにさまざまな技法の習熟度をさらに上げたい方のための実践塾~ 【2015/11/26(木)】
 
Manual de instrucciones Atica
Manual de instrucciones AticaManual de instrucciones Atica
Manual de instrucciones Atica
 
RTA (Ready to Assemble)
RTA (Ready to Assemble)RTA (Ready to Assemble)
RTA (Ready to Assemble)
 
Mi credo pedagógico. J.D
Mi credo pedagógico. J.DMi credo pedagógico. J.D
Mi credo pedagógico. J.D
 

Similaire à Entities on Node.JS

Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation ProcessingJintin Lin
 
Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumAxway Appcelerator
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Mahmoud Hamed Mahmoud
 
S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0Sun-Jin Jang
 
Event driven application
Event driven applicationEvent driven application
Event driven applicationChris Saylor
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 
ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013Mathias Seguy
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxudithaisur
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - AndroidWingston
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application ArchitectureMark Trostler
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSarah El-Atm
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockRichard Lord
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patternsSamuel ROZE
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinBarry Gervin
 
Blogging tizen devlab@seoul ppt - optimization
Blogging   tizen devlab@seoul ppt - optimizationBlogging   tizen devlab@seoul ppt - optimization
Blogging tizen devlab@seoul ppt - optimizationJin Yoon
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.Mark Rees
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya Patsovska
 
Flutter Forward EXTENDED - Flutter로 앱 개발 입문하기
Flutter Forward EXTENDED -  Flutter로 앱 개발 입문하기Flutter Forward EXTENDED -  Flutter로 앱 개발 입문하기
Flutter Forward EXTENDED - Flutter로 앱 개발 입문하기SuJang Yang
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rulesSrijan Technologies
 

Similaire à Entities on Node.JS (20)

Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend Titanium
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0
 
Event driven application
Event driven applicationEvent driven application
Event driven application
 
Android For All The Things
Android For All The ThingsAndroid For All The Things
Android For All The Things
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event Dispatcher
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
Blogging tizen devlab@seoul ppt - optimization
Blogging   tizen devlab@seoul ppt - optimizationBlogging   tizen devlab@seoul ppt - optimization
Blogging tizen devlab@seoul ppt - optimization
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Flutter Forward EXTENDED - Flutter로 앱 개발 입문하기
Flutter Forward EXTENDED -  Flutter로 앱 개발 입문하기Flutter Forward EXTENDED -  Flutter로 앱 개발 입문하기
Flutter Forward EXTENDED - Flutter로 앱 개발 입문하기
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 

Dernier

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Entities on Node.JS

  • 3. Entities useEntities use CIP ​for Classical Inheritance /thanpolas/cip Bluebird for the 100% Promises API /petkaantonov/bluebird Middlewarify for creating middleware /thanpolas/middlewarify
  • 5. Creating an EntityCreating an Entity var entity = require('entity'); var EntityChild = entity.extend(function() { this.a = 1; }); var EntityGrandChild = EntityChild.extend(); entity.extend var entity = require('entity'); var UserEntity = entity.extendSingleton(function() {}); /* ... */ var userEnt = UserEntity.getInstance(); entity.extendSingleton
  • 6. Entities AdaptorsEntities Adaptors MongooseMongoose MongoDB ORM http://mongoosejs.com/ SequelizeSequelize PostgreSQL MySQL MariaDB SQLite http://sequelizejs.com/
  • 7. CRUD PrimitivesCRUD Primitives create(data) read(query=) readOne(query) readLimit(?query, offset, limit) update(query, updateValues) delete(query) count(query=)
  • 8. CRUD PrimitivesCRUD Primitives create()create() entity.create({name: 'thanasis'}) .then(function(udo) { udo.name === 'thanasis'; // true }) .catch(function(error) { // deal with error. }); ... so on and so forth ...
  • 9. Entity HooksEntity Hooks Middlewarify in action before after last
  • 10. Entity HooksEntity Hooks beforebefore // a middleware with synchronous resolution entity.read.before(function(data){ if (!data.name) { throw new TypeError('No go my friend'); } }); // then... entity.read({}).then(function(document) { // you'll never get here }, function(err) { err instanceof Error; // true err.message === 'No go my friend'; // true });
  • 11. Hooks are FiFoHooks are FiFo Order MATTERSOrder MATTERS
  • 13. Before HooksBefore Hooks Get the exact same number or arguments After & Last HooksAfter & Last Hooks Gets the result plus the original number or arguments
  • 14. Entity HooksEntity Hooks AsynchronicityAsynchronicity entity.create.before(function(data){ return promiseReturningFn(function(result) { resolve(result + 1); }); });
  • 15. Extending EntitiesExtending Entities adding new methodsadding new methods
  • 16. Extending EntitiesExtending Entities Just use the prototypeJust use the prototype var Entity = require('entity'); var UserEntity = module.exports = Entity.extend(); UserEntity.prototype.report = function(userId) { return promiseReturningAction(userId); };
  • 17. Extending EntitiesExtending Entities Using method()Using method() var Entity = require('entity'); var UserEntity = module.exports = Entity.extend(function() { this.method('report', this._report.bind(this)); this.report.before(this._checkUserId.bind(this)); this.report.after(this._normalize.bind(this)); }); UserEntity.prototype._report = function(userId) { return promiseReturningAction(userId); };
  • 18. Let's combine all upLet's combine all up
  • 19. var ClipEntity = module.exports = EntityBase.extendSingleton(function() { this.setModel(clipModel.Model); this.method('readOneApi', this.readOne); this.method('readLimitApi', this.readLimit); this.method('updateApi', this.update); this.method('readApi', this.read); // Apply system wide (global) filters this.readLimitApi.before(this.systemFilter.bind(this)); this.readOneApi.before(this.systemFilter.bind(this)); // Clip Creation middleware this.create.before(this._populateActiveEvent.bind(this)); this.create.after(this._processNewClip.bind(this)); // Record sanitization middleware this.updateApi.after(helpers.skipArgs(this.sanitizeResult, 2, this)); this.readLimitApi.after(helpers.skipArgs(this.sanitizeResults, 3, this)); this.readOneApi.after(helpers.skipArgs(this.sanitizeResult, 1, this)); }); A Production-ish EntityA Production-ish Entity
  • 20. Entity Hands OnEntity Hands On this.readLimitApi.before(this.systemFilter.bind(this)); /** * Apply system filters in all incoming READ queries * to exclude deleted and corrupt items. * * @param {Object} query The query. */ ClipEntity.prototype.systemFilter = function(query) { query.notFound = { ne: true }; query.processed = true; };
  • 21. Entity Hands OnEntity Hands On this.create.after(this._processNewClip.bind(this)); /** * Post creation clip processing. * * @param {Object} data Item used to create the record. * @param {app.entity.ClipProcess} processEnt The process entity. * @param {mongoose.Document} clipItem The result. * @return {Promise} A promise. * @private */ ClipEntity.prototype._processNewClip = Promise.method(function(data, processEnt, clipItem) { processEnt.clipId = clipItem.id; log.finest('_processNewClip() :: Clip Saved to DB, starting FS save...', clipItem.id); return this._checkWatermarkAndStore(processEnt, clipItem) .bind(processEnt) .then(processEnt.createThumbnail) .then(processEnt.checkS3) .then(processEnt.updateDatabase) .then(function() { log.fine('_processNewClip() :: Clip processing finished:', processEnt.sourceFilePath); }) .catch(processEnt.moveToTrash) .catch(processEnt._deleteRecord); });
  • 22. Now let's get crazyNow let's get crazy
  • 23. EntitiesEntities ++ CrudeCrude POST /user GET /user GET /user/:id PUT /user/:id PATCH /user/:id DELETE /user/:id /thanpolas/crude
  • 24. ... but not today... but not today
  • 25. Thank you (here is where you applaud) Thanasis Polychronakis @thanpolas http://www.slideshare.net/thanpolas
  • 26. Questions? Be a critic Thanasis Polychronakis @thanpolas http://www.slideshare.net/thanpolas
  • 27. Shameless Plug Time Promo Code bgwebsummit From 60€ --> 40€ 15/5/2015 @ Thessaloniki Greece devitconf.org