Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Webinar: Get Started with the MEAN Stack

In this session, we will walk through building a REST API from scratch with the MEAN stack using the test-driven development approach. We’ll cover MongoDB’s document model, the Mongoose object document mapper, and testing with Mocha and Superagent as we build a mobile shopping cart application. You'll walk away with an understanding of how to build your first app on MongoDB using the MEAN stack.

Related Books

Free with a 30 day trial from Scribd

See all
  • Be the first to comment

Webinar: Get Started with the MEAN Stack

  1. 1. Developing a Basic REST API from Scratch Using TDD Valeri Karpov Node.js Engineer, MongoDB www.thecodebarbarian.com github.com/vkarpov15 @code_barbarian
  2. 2. * What is this talk about? •MongoDB is great for storing web/mobile app data •So let’s build a REST API using Node.js! •+ learn a bit about test-driven dev with Node.js •+ learn two MongoDB schema design principles •Server-side only - just JSON, no HTML •No AngularJS part, focus more on MongoDB •Upcoming EdX course
  3. 3. * Overview •Part 1: Shopping Cart Application –Search for products –Add them to your cart –Check out with Stripe •Part 2: Using the Mongoose ODM •Part 3: Schema Design •Part 4: Building an API with the Express framework •Part 5: Testing with Mocha + Superagent
  4. 4. * Part 1: What Does the App Do?
  5. 5. * What Does the App Do?
  6. 6. * What Does the App Do?
  7. 7. * App Structure •"Bad programmers worry about the code. Good programmers worry about data structures and their relationships." - Linus Torvalds •3 schemas for 3 collections: •Products •Categories •Users
  8. 8. * Schema Relationships •Product belongs to one or more categories •Users can have multiple products in their cart •Representing relationships in MongoDB is tricky •But that’s what mongoose is for
  9. 9. * Part 2: Using the Mongoose ODM •“Object document mapper” (like ORM, but for MongoDB) •“MongoDB object modeling designed to work in an asynchronous environment” •Written for Node.js •Provides schema validation, pseudo-JOINs, etc.
  10. 10. * Brief Overview of Node.js •require() • Async I/O
  11. 11. * What Does Async Mean? Register event handler In node.js, you don’t execute I/O imperatively. You register a callback to execute when the I/O is done Prints before “done reading”
  12. 12. * Your First Mongoose Schema matches X@Y.Z
  13. 13. * Using Your Schema Create User Save user to MongoDB Load user from MongoDB Print user to stdout
  14. 14. * Part 2 Takeaways •Mongoose provides several neat features –Model part of MVC –Default values –Schema validation and declarative schema design
  15. 15. * Part 3: Schema Design •3 schemas: –Product –Category –User •Going to use mongoose to define schemas •Will use a couple key schema design principles
  16. 16. * Product Schema
  17. 17. * Product Schema in Action
  18. 18. * Category Schema
  19. 19. * Category Schema Queries •What categories are descendants of “Electronics”? • •What categories are children of “Non-Fiction”? • •What categories are ancestors of “Phones”?
  20. 20. * Product + Category Schemas
  21. 21. * Category Schema Takeaways •Queries in MongoDB should be simple •Strive for minimal data transformation by server •“Store what you query for” •“If you need [the aggregation framework in a heavily used API endpoint], you're screwed anyway, and should fix your program.” - Linus Torvalds •Good for performance and developer sanity
  22. 22. * User Schema User’s cart as an array of ObjectIds...
  23. 23. * Principle of Least Cardinality •Product and user = many-to-many relationship •Don’t necessarily need a mapping table •User won’t have 1000s of products in cart •Can represent relationship as array in user since one side is small •If one side of many-to-many is bounded and/or small, it is a good candidate for embedding •Arrays that grow without bound are an antipattern! –16mb document size limit –network overhead
  24. 24. * Part 4: The Express Framework •Most popular Node.js web framework •Simple, pluggable, and fast •Great tool for building REST APIs
  25. 25. * Your First Express App Route Parameter
  26. 26. * What is REST? •Representational State Transfer •HTTP request -> JSON HTTP response •Business logic on top of MongoDB schemas –Access control, emails, analytics, etc.
  27. 27. * Structuring Your REST API
  28. 28. * GET /category/id/:id Find Category Error handling Output JSON
  29. 29. * GET /category/parent/:id
  30. 30. * GET /product/category/:id
  31. 31. * Adding Products to User’s Cart •Recall cart is an array of products
  32. 32. * Adding Products to User’s Cart Get cart from HTTP request Overwrite user’s cart Let mongoose handle casting and validating data
  33. 33. * PUT /me/cart Takeaways •Mongoose lets you be lazy •Access control using subdocs
  34. 34. * Bonus: Stripe Checkout Create a Stripe charge with the npm ‘stripe’ module
  35. 35. * Bonus: Stripe Checkout Error handling Empty user cart on success
  36. 36. * Part 4 Takeaways •Express REST API on top of mongoose –Access control –Business logic –Define what operations user can take on database •Mongoose casting and validation for APIs
  37. 37. * Part 5: Test-Driven Development •Building an API is tricky •Lots of different error conditions •Express has a lot of magic under the hood
  38. 38. * NodeJS Concurrency and Testing •Node.js runs in an event loop •Single threaded •Can run client and server on same thread! –Client sends HTTP request –Client registers a callback awaiting the result –Server’s “on HTTP request” event handler is triggered –Server sends response, continues waiting for events –Client’s callback gets fired •Test server end-to-end
  39. 39. * Superagent •NodeJS HTTP client •Isomorphic: runs in both browser and NodeJS •Same author as Express
  40. 40. * Mocha •Testing Framework for NodeJS •Same author as Express •BDD-style syntax –describe() -> test suite –it() -> individual test
  41. 41. * Setting Up Category API Tests
  42. 42. * Testing GET /category/id/:id
  43. 43. * Part 5 Takeaways •NodeJS concurrency makes testing easy •Not just unit tests - full E2E for your REST API •Can manipulate database and make arbitrary HTTP requests
  44. 44. * •Upcoming EdX Video Course •Slides on http://www.slideshare.net/vkarpov15 •Looking for beta testers! Sign up for notifications –http://goo.gl/forms/0ckaJ4YvJN •Interested in learning about AngularJS? –Professional AngularJS on Amazon •More NodeJS+MongoDB content at: –www.thecodebarbarian.com –Twitter: @code_barbarian Thanks for Listening!

×