Adapter Pattern

Concepts

Adapter Pattern

The Adapter Pattern allows incompatible interfaces to work together. There are many persistent storage options with incompatible interfaces, so a single program that knows how to talk to every kind of database would consist of a hard-to-maintain monolithic code base and would be slow to evolve. Not a good idea. JSData solves this problem by using the Adapter Pattern, which allows JSData to work with many persistence layers while keeping individual code bases smaller, more focused, and easier to maintain.

👍

Tip

By itself JSData can't talk to databases. Instead JSData (js-data.js) defines a CRUD interface, and JSData's adapters provide the implementations, i.e. js-data-rethinkdb.js, js-data-firebase.js, etc.

The Adapter Pattern works by defining a single interface and then writing an adapter for each incompatible interface. Each adapter bridges the gap between two interfaces. JSData (the ORM) defines an interface, and JSData's adapters implement that interface. Each adapter provides the implementation necessary for JSData to be able to talk to a particular persistence layer.

👍

Tip

The js-data-adapter project defines the adapter interface and provides an abstract Adapter class that individual adapters can extend.

Take creating and saving a new record for example: JSData defines a create method, but creating and saving a new record in MySQL is different from RethinkDB is different from localStorage is different from Firebase and so on and so forth. JSData itself can't contain all the logic to know how to create and save new records in MySQL, RethinkDB, localStorage, Firebase, etc. because it would be a huge mess. Instead, JSData defines an interface for create, and adapters provide the implementation. JSData defines:

  • create is a method
  • create accepts two arguments
    • props - The properties from which to create the new record.
    • options - Configuration options.
  • create returns a Promise, which either:
    • resolves with the newly created record
    • rejects due to some error

When you call JSData's create method, it in turn calls an adapter's create method, which then does the heavy lifting of saving a new record. This flexibility allows adapters to improve and evolve independent of each other and of JSDa​ta, and allows you to switch databases (just swap adapters) without having to rewrite your whole data layer.