Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building Enterprise JavaScript Applications

You're reading from  Building Enterprise JavaScript Applications

Product type Book
Published in Sep 2018
Publisher Packt
ISBN-13 9781788477321
Pages 764 pages
Edition 1st Edition
Languages
Author (1):
Daniel Li Daniel Li
Profile icon Daniel Li

Table of Contents (26) Chapters

Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
1. The Importance of Good Code 2. The State of JavaScript 3. Managing Version History with Git 4. Setting Up Development Tools 5. Writing End-to-End Tests 6. Storing Data in Elasticsearch 7. Modularizing Our Code 8. Writing Unit/Integration Tests 9. Designing Our API 10. Deploying Our Application on a VPS 11. Continuous Integration 12. Security – Authentication and Authorization 13. Documenting Our API 14. Creating UI with React 15. E2E Testing in React 16. Managing States with Redux 17. Migrating to Docker 18. Robust Infrastructure with Kubernetes 1. Other Books You May Enjoy Index

Moving common logic into middleware


Let's see how we can improve our code further. If you examine our Create User endpoint handler, you may notice that its logic could be applied to all requests. For example, if a request comes in carrying a payload, we expect the value of its Content-Type header to include the string application/json, regardless of which endpoint it is hitting. Therefore, we should pull that piece of logic out into middleware functions to maximize reusability. Specifically, these middleware should perform the following checks:

  • If a request uses the method POSTPUT or PATCH, it must carry a non-empty payload.
  • If a request contains a non-empty payload, it should have its Content-Type header set. If it doesn't, respond with the 400 Bad Request status code.
  • If a request has set its Content-Type header, it must contain the string application/json. If it doesn't, respond with the 415 Unsupported Media Type status code.

 

Let's translate these criteria into Cucumber/Gherkin specifications...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}