Chapter 5. Coffee with Strangers

In this chapter, we will write an API that allows users to go for a coffee! This comprises of a simple yet extendable user matching system.

Initially, we'll just ask the user to enter their name and e-mail, which is stored on MongoDB. Whenever we can match these with the nearest other user, e-mails are sent to both sides and then it's coffee time. After we set up the base, it's time to make sure we keep a record of the matches and avoid duplicates from happening for a better user experience.

Soon after, let's make ourselves ready to go global and take into account their geo positioning.

Assuming everything goes well (which is a mistake), we are validated. So it's time to refactor to a more maintainable architecture, where the pairing becomes a service by itself.

Finally, let's allow our users to rate how their meeting was and tell us whether it was a successful meeting or not in real-world applications, the usage of user generated feedback is invaluable!

We expect that this sort of application structure will offer the reader inspiration to create real world matching applications.

Code structure

Before getting into actual code, we want to provide a heads up on the structure for the code in this chapter, which is a bit different than before, and we hope it adds another view to structure code for Express and Node.js in general.

Some may call it a Factory pattern; it consists of wrapping each of the file's code with a function that can be used to configure or test it. While this requires a bit more of scaffolding, it frees our code from depending on a static state. It will often look as follows:

'''javascript
module.exports = function (dependency1){
  // these will be public
  var methods = {}

  // individual for each instance
  var state = 0

  // some core functionality of this file
  methods.addToState = function(x) {
    state += x
  };

  methods.getResult = function() {
    return dependency1.getYforX(state)
  };

  return methods
}
'''

A corollary of this structure is that each invocation of this file will have its own state, exactly like the instance of a class, except we don't depend on this, but the scope that never goes missing.

Going a bit further, we'll try centralizing the structure of the pieces per folder, each with a respective index.js, the main responsibilities of which are to initialize instances when needed, keep references to dependencies that will be passed down, and return only public methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.194.106