This document discusses best practices for developing Node.js applications. It recommends using frameworks like Express for building web apps, libraries like Async to avoid callback hell, and organizing code into modular sub-applications. It also covers testing, error handling, documentation, and open-sourcing projects. Standards like Felix's Style Guide and domain-driven design principles are advocated. Communication channels like events, HTTP APIs, and WebSockets are examined.
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
In the coming two weeks I will do a series of talks at various conferences in Austria and Germany. I will speak about AngularJS, TypeScript, and Windows Azure Mobile Services. In this blog post I publish the slides and the sample code.
Vue.js + Django - configuración para desarrollo con webpack y HMRJavier Abadía
Presentación del meetup de Vue.js en Madrid, el 12/Sep/2017 donde explicamos cómo configurar Django y webpack para desarrollar SPAs con Vue.js y backend con Django: incluye configuración de Hot-Module-Reloading, autenticación, API y rutas.
El código de ejemplo se puede encontrar aquí: https://github.com/jabadia/gif_catalog
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
In the coming two weeks I will do a series of talks at various conferences in Austria and Germany. I will speak about AngularJS, TypeScript, and Windows Azure Mobile Services. In this blog post I publish the slides and the sample code.
Vue.js + Django - configuración para desarrollo con webpack y HMRJavier Abadía
Presentación del meetup de Vue.js en Madrid, el 12/Sep/2017 donde explicamos cómo configurar Django y webpack para desarrollar SPAs con Vue.js y backend con Django: incluye configuración de Hot-Module-Reloading, autenticación, API y rutas.
El código de ejemplo se puede encontrar aquí: https://github.com/jabadia/gif_catalog
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
Ember applications are built around an MVC model that prescribes Models, Views, Controllers, and Routes for managing persistence, DOM, application state, and URLs. In an ambitious enough app, that model may fail to cover the whole problem space. Fear not, for in this presentation you will learn how to use Ember’s container and dependency features to move beyond MVC, as well as learning how they tie Ember internals together.
Video: http://www.youtube.com/watch?v=iCZUKFNXA0k&feature=youtu.be&t=1h45m59s
Mathilde Lemée & Romain Maton
La théorie, c’est bien, la pratique … aussi !
Venez nous rejoindre pour découvrir les profondeurs de Node.js !
Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui !
http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html
It's silly to write the same functionality over and over again. Auth is the most often implemented functionality at web projects. Let's check how can we speed up development by using one of auth provider: Amazon Cognito, Google Firebase or Auth0. On code level we will use custom React Hooks.
A look at how HTML5 aims to plug the holes that Flash has been filling in browsers for the last decade, looking at both HTML5 and non-HTML5 JavaScript APIs.
For Flash Brighton in Feb 2010.
Django + Vue, JavaScript de 3ª generación para modernizar DjangoJavier Abadía
Slides de la charla que di en la PyConEs 2017 en Cáceres, el 24 de Septiembre.
Explicaba cómo montar un entorno de desarrollo ágil con Django en el back, Vue en el front y webpack para empaquetar el front y proporcionar Hot Module Reloading
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergXebia Nederland BV
This live demo will introduce Mox: the versatile mocking framework for simplifying unit and view testing you AngularJS applications. You'll see how you can reduce boilerplate in your tests and simplify testing your AngularJS components in isolation.
You'll also be shown how Mox can help you test your AngularJS views. By doing view testing you'll be able to catch errors in your views early instead of at the latest point in your e2e tests
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
"As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications" così si presenta Node.js, piattaforma tecnologica che - grazie alla sua immediatezza e produttività - ha conquistato dapprima startup e piccole aziende, fino a ritagliarsi uno spazio importante in realtà come IBM, LinkedIn, Netflix e Yahoo. La stessa Microsoft ha riconosciuto le potenzialità della piattaforma, tanto da integrare Node.js in Visual Studio Code e nelle ultime release di Visual Studio, oltre a basarci alcuni dei propri servizi di Azure come "Mobile Services" e "Functions".
In questa sessione vedremo come implementare con Node.js alcuni scenari applicativi comuni nell’ambito dello sviluppo web, analizzando quando la sua adozione può portarci vantaggi nel nostro lavoro quotidiano. In conclusione, faremo una breve panoramica architetturale, descrivendo alcuni scenari di cooperazione tra .NET e Node.js nello stesso sistema.
Codice e demo: https://github.com/rucka/CommunityDays2016
Ember applications are built around an MVC model that prescribes Models, Views, Controllers, and Routes for managing persistence, DOM, application state, and URLs. In an ambitious enough app, that model may fail to cover the whole problem space. Fear not, for in this presentation you will learn how to use Ember’s container and dependency features to move beyond MVC, as well as learning how they tie Ember internals together.
Video: http://www.youtube.com/watch?v=iCZUKFNXA0k&feature=youtu.be&t=1h45m59s
Mathilde Lemée & Romain Maton
La théorie, c’est bien, la pratique … aussi !
Venez nous rejoindre pour découvrir les profondeurs de Node.js !
Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui !
http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html
It's silly to write the same functionality over and over again. Auth is the most often implemented functionality at web projects. Let's check how can we speed up development by using one of auth provider: Amazon Cognito, Google Firebase or Auth0. On code level we will use custom React Hooks.
A look at how HTML5 aims to plug the holes that Flash has been filling in browsers for the last decade, looking at both HTML5 and non-HTML5 JavaScript APIs.
For Flash Brighton in Feb 2010.
Django + Vue, JavaScript de 3ª generación para modernizar DjangoJavier Abadía
Slides de la charla que di en la PyConEs 2017 en Cáceres, el 24 de Septiembre.
Explicaba cómo montar un entorno de desarrollo ágil con Django en el back, Vue en el front y webpack para empaquetar el front y proporcionar Hot Module Reloading
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergXebia Nederland BV
This live demo will introduce Mox: the versatile mocking framework for simplifying unit and view testing you AngularJS applications. You'll see how you can reduce boilerplate in your tests and simplify testing your AngularJS components in isolation.
You'll also be shown how Mox can help you test your AngularJS views. By doing view testing you'll be able to catch errors in your views early instead of at the latest point in your e2e tests
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
"As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications" così si presenta Node.js, piattaforma tecnologica che - grazie alla sua immediatezza e produttività - ha conquistato dapprima startup e piccole aziende, fino a ritagliarsi uno spazio importante in realtà come IBM, LinkedIn, Netflix e Yahoo. La stessa Microsoft ha riconosciuto le potenzialità della piattaforma, tanto da integrare Node.js in Visual Studio Code e nelle ultime release di Visual Studio, oltre a basarci alcuni dei propri servizi di Azure come "Mobile Services" e "Functions".
In questa sessione vedremo come implementare con Node.js alcuni scenari applicativi comuni nell’ambito dello sviluppo web, analizzando quando la sua adozione può portarci vantaggi nel nostro lavoro quotidiano. In conclusione, faremo una breve panoramica architetturale, descrivendo alcuni scenari di cooperazione tra .NET e Node.js nello stesso sistema.
Codice e demo: https://github.com/rucka/CommunityDays2016
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
09 - Express Nodes on the right Angle - Vitaliy Basyuk - IT Event 2013 (5)
60 вузлів під правильним кутом - миттєва розробка програмних додатків використовуючи Node.js + Express + MongoDB + AngularJS.
Коли ми беремось за новий продукт, передусім ми думаємо про пристрасть, яка необхідна йому, щоб зробити користувача задоволеним і відданим нашому баченню. А що допомагає нам здобути прихильність користувачів? Очевидно, що окрім самої ідеї, також важлими будуть: зручний користувацький інтерфейс, взаємодія в реальному часі та прозора робота з даними. Ці три властивості ми можемо здобути використовучи ті чи інші засоби, проте, коли все лиш починається, набагато зручніше, якщо інструменти допомагають втілити бажане, а не відволікають від головної мети.
Ми розглянемо процес розробки, використовуючи Node.js, Express, MongoDB та AngularJS як найбільш корисного поєднання для отримання вагомої переваги вже на старті вашого продукту.
Віталій Басюк
http://itevent.if.ua/lecture/express-nodes-right-angle-rapid-application-development-using-nodejs-express-mongodb-angular
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
HA websites are where the rubber meets the road - at 200km/h. Traditional separation of dev and ops just doesn't cut it.
Everything is related to everything. Code relies on performant and resilient infrastructure, but highly performant infrastructure will only get a poorly written application so far. Worse still, root cause analysis in HA sites will more often than not identify problems that don't clearly belong to either devs or ops.
The two options are collaborate or die.
This talk will introduce 3 core principles for improving collaboration between operations and development teams: consistency, repeatability, and visibility. These principles will be investigated with real world case studies and associated technologies audience members can start using now. In particular, there will be a focus on:
- fast provisioning of test environments with configuration management
- reliable and repeatable automated deployments
- application and infrastructure visibility with statistics collection, logging, and visualisation
Session highlighting and demonstrating approaches to common challenges in modern portlet development. Topics include AJAX in JSR-168 and JSR-286 portlets, CSS and Javascript toolkits, security, and optimization of front-end resources. This session was presented at the Jasig Spring 2010 conference in San Diego, CA by Jennifer Bourey.
Dans cette conférence de 45 minutes que j'ai donnée à BlendWebMix 2018, je partage les bonnes pratiques React.js que nous avons apprises grâce à react-admin.
La vidéo de cette conférence est disponible ici: https://youtu.be/NX3puR_kERc
REST est devenu un standard pour les APIs web. Mais malgré sa popularité, il est plein de défauts. Son successeur existe et il vient de Facebook. Venez découvrir en détail le principe, la mise en oeuvre et l’écosystème de GraphQL.
La blockchain, quand l'individu sert au collectif... malgré luiFrancois Zaninotto
La blockchain, tout le monde en parle mais qu'est-ce que c'est, comment ça marche, et à quoi ça sert ? Et si la blockchain était le déclencheur d'un profond changement de société ?
Sans langue de bois, avec des exemples concrets et plein de dessins, cette conférence vous aidera à vous décider si vous avez intérêt à parier sur cette technologie dans les années à venir.
En client-serveur traditionnel, chaque action de l'utilisateur induit un recalcul de toute la page côté serveur, puis le transport du HTML vers le navigateur. PHP et ses frameworks MVC sont conçus pour gérer cette architecture. Mais quand AJAX et HTML5 viennent bouleverser la répartition de ce qui se fait côté client et côté serveur, il est temps de repenser nos outils. Quelle part de nos frameworks reste pertinente dans une architecture API-centric? PHP est-il condamné à ne servir que des APIs REST? Et quelles architectures côté client peuvent prendre le relais sans faire exploser la complexité de développement ? Paradoxalement, c'est du monde du jeu vidéo que viendra peut-être la clé des applications de demain. Une conférence sans code, mais avec des dessins. Et des idées pour demain.
Les frameworks de développement web, on les aime, on les déteste. Quand jQuery est sorti, c'était une révolution. Aujourd'hui beaucoup de lead developers conseillent de ne pas l'utiliser. Il faut dire que les frameworks donnent naissance à des débats passionnés.
Dans le monde PHP, c'est pareil : Symfony, Zend Framework ou Laravel ? Derrière ces questions se cachent des choix cruciaux : WTF contre RAD, vitesse contre expressivité, facilité d'utilisation contre facilité d'intégration... Un framework est toujours un compromis fait à un instant donné pour aider ses utilisateurs sans se mettre en travers de leur chemin.
Mais les besoins des développeurs changent. C'est pourquoi les frameworks doivent aussi changer. Après une brève histoire des frameworks de développement depuis les années 2000, nous essaierons de découvrir ensemble quelles sont les tendances dans l'évolution des frameworks, de comprendre où ils nous mèneront dans quelques années, et si vous aurez à les utiliser...
Vous ne manquez pas de tutoriels pour écrire un "Hello, world" avec n'importe quel framework. Mais que se passe-t-il quand, sur cette base, vous faites travailler une équipe de 4 développeurs pendant 6 mois ? Petit retour d'expérience sur l'architecture logicielle d'une application Symfony2 de taille moyenne, avec des visualisations inédites et des indices pour répondre à cette éternelle question : mais où je le mets ce code ?
Présentation effectuée au PHP Tour Lyon 2014
Remplacer un SI existant par un nouvel outil basé sur l'état de l'art (Symfony CMF, ElasticSearch, RabbitMQ, Docker, Backbone.js) sans reculer sans cesse la mise en production, c'est une question d'agilité. Concevoir l'architecture, découvrir des stratégies de migration partielle, investir dans des systèmes de synchronisation, partager l'avancée d'un projet avec tous, former les équipes au nouvel outil, accompagner les changements dans l'organisation de l'entreprise, voici quelques recettes de migration continue illustrées par le cas du CMS de 20Minutes.fr.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
5. Organisation du code
Objectif: éviter le code spaghetti
Utiliser un framework pour les applis web
visionmedia/express (ou viatropos/tower)
Eviter la course aux callbacks
caolan/async (ou kriskowal/q)
Inclure des routes et monter des sous-applications
«Fat model, Skinny controller»
Modules de service pour éviter un modèle trop fat
6. // main app.js
var express = require('express');
var app = module.exports = express.createServer();
app.configure(function(){
app.use(app.router);
// these middlewares are required by some of the mounted apps
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'qdfegfskqdjfhskjdfh' }));
});
// Routes
app.use('/api', require('./app/api/app'));
app.use('/dashboard', require('./app/dashboard/app'));
app.get('/', function(reaq, res) {
res.redirect('/dashboard/events');
});
app.listen(3000);
15. Canaux de communication
Dans un module
Entre applications Client / Serveur
ou une application
Appels de
Notifications Events socket.io
méthodes
Echanges de Appels de XMLHTTP
API HTTP
données méthode Request
Traitements
Promise AMQP Mentir*
asynchrones
16. // server-side
var socketIo = require('socket.io');
var CheckEvent = require('./models/checkEvent');
var io = socketIo.listen(app);
CheckEvent.on('postInsert', function(event) {
io.sockets.emit('CheckEvent', event.toJSON());
});
18. Gestions des erreurs
try {} catch {} ne marche pas en asynchrone
function (err, results) est la signature
standard des callbacks asynchrones
"Leave early"
Utiliser les codes d’erreur HTTP pour les APIs
19. app.delete('/check/:id', function(req, res, next) {
Check.findOne({ _id: req.params.id }, function(err, check) {
if (err) {
return next(err);
}
if (!check) {
return next(new Error('No check with id ' + req.params.id));
}
check.remove(function(err2){
if (err2) {
req.flash('error', 'Error - Check not deleted');
res.redirect('/checks');
return;
}
req.flash('info', 'Check has been deleted');
res.redirect('/checks');
});
});
});
20. Tests Unitaires
Librairies (presque) standard
Assertions : visionmedia/should.js (ou node/assert)
TDD : visionmedia/mocha (ou caolan/node-unit)
BDD : visionmedia/mocha (ou mhevery/jasmine-node)
L’asynchrone se teste aussi très bien
Pas besoin de mocker quand on peut monkey-patcher
21. describe('Connection', function(){
var db = new Connection
, tobi = new User('tobi')
, loki = new User('loki')
, jane = new User('jane');
beforeEach(function(done){
db.clear(function(err){
if (err) return done(err);
db.save([tobi, loki, jane], done);
});
})
describe('#find()', function(){
it('respond with matching records', function(done){
db.find({ type: 'User' }, function(err, res){
if (err) return done(err);
res.should.have.length(3);
done();
})
})
})
})
23. Projet open-source
Configurable
app.configure() pas compatible avec un SCM
lorenwest/node-config (ou flatiron/nconf)
Extensible
Custom events
Plugin architecture
24. // in main app.js
path.exists('./plugins/index.js', function(exists) {
if (exists) {
require('./plugins').init(app, io, config);
};
});
// in plugins/index.js
exports.init = function(app, io, config) {
require('./console').init();
}
25. module.exports = exports = function lifecycleEventsPlugin(schema) {
schema.pre('save', function (next) {
var model = this.model(this.constructor.modelName);
model.emit('preSave', this);
this.isNew ? model.emit('preInsert', this) :
model.emit('preUpdate', this);
this._isNew_internal = this.isNew;
next();
});
schema.post('save', function() {
var model = this.model(this.constructor.modelName);
model.emit('postSave', this);
this._isNew_internal ? model.emit('postInsert', this) :
model.emit('postUpdate', this);
this._isNew_internal = undefined;
});
schema.pre('remove', function (next) {
this.model(this.constructor.modelName).emit('preRemove', this);
next();
});
schema.post('remove', function() {
this.model(this.constructor.modelName).emit('postRemove', this);
});
};
26. Questions ?
François Zaninotto
@francoisz http://github.com/fzaninotto