- JavaScript 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .skales | ||
| lib | ||
| tests | ||
| .babelrc | ||
| .eslintrc.json | ||
| .gitignore | ||
| .gitlab-ci.yml | ||
| .jsbeautifyrc | ||
| .npmrc | ||
| CHANGELOG.md | ||
| CONTRIBUTING.md | ||
| index.js | ||
| jsconfig.json | ||
| LICENSE | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
Moleculer ORE
Sommaire
Introduction
Moleculer ORE is a Javascript library which allow developpers to easily build highly structured databases, designed for gui and web applications.
the ORE was designed to work with the molecular JS microservices framework, thought, this is not the exclusive way to use it.
Philosophy
We don't really like select queries. Instead, Moleculer ORE provides an observer/observable based-API. Instead of making shitloads of requests each time you need to display stuff, you just ask the server to provide you thematical ressources and to keep you up to date.
When the data is modified, the server sends you directly the fresh news so you never have to worry about what you have in hand.
Database export, import and migration made easily
Moleculer ORE offers builtin support for keeping your databases up to date and give old stuff a new fancy look.
A new look on database models
Instead of using traditional entity-association model, Moleculer ORE use a custom model designed specifically for web applications development.
This model is based on two simple idea : Trees and hierarchy.
You can easily visualize your schemas, in plain text or using our dotfiles generator and feeding graphviz with them.
Tutorial
Configuraton
The environment variable BACKSTAGE_MODEL_NO_WARN can be set to disable warnings when loading or creating a model
Get started
You will need a SGBD, like mariaDB and postgresSQL properly installed and configured.
Put this example .env file to your NPM project root
host=localhost
user=test
password=test
Here is some bootstraping magic :
//import needed stuff
import { Manager, metamodelBuilder, uuid, loaders, Model } from "../index.js"
//Instanciate a Model object
const model = new Model("mymodel", "0.0.1")
//Load the model from .YAML description file
loaders.yaml(model).loadFolder("/models/mymodel").build()
//Log the model
model.log()
//print the model as dotFile. You can visualiẑe this with IDE extension or by using graphviz
await model.toDot().toFile("./")
//Start the manager
const manager = new Manager(model)
await manager.start()
//Create a database called test_db
await manager.createBase("test_db")
//Get the Database manipulation API
const db = await manager.db("test_db")
Building a model
Write your schemas as YAML files :
A person :
type: person
fields:
lastName: STRING
firstName: STRING
birthDate: DATE
mail: STRING
phone: STRING
hobbies: STRING SET
relations:
lover: REF(person)
friends: LIST(person)
You can see that you can have both simple type and collection type. In this example, hobbies is a set, which is a list of uniques elements.
There is two other collection types : map and array, which are exactly what their names says. Map can only have string keys.
A society with a list of departments:
type: society
fields:
name: STRING
relations:
departments: LIST(department) OWNER
The owner property means that departments cannot exist without the society. Therefore :
- the departement will be deleted if the society is deleted.
- When updating a society, you will be able to override departments in the list.
You can see an owner relation as an exclusive composition or aggregation relation.
A relation can also have the warder property, which means that the entity record is protecting another entity recorde, member of another arborescence or hierarchical structure. Said entity will throw an error on deletion attempt, unless the relation is broken first.
You can see a warder relation as an non-exclusive composition or aggregation relation.
A relation can also have the lover property. An entity which love another entity will be deleted if the entity is deleted.
You can see a lover relation as an extension relation.
A relation can be an union of two relation, that is what we call a fork.
Here such a relation :
type: person
fields:
firstName: STRING
lastName: STRING
relations:
student: REF(student) OWNER
professor: REF(professor) OWNER
mutations:
data: FORK(student, professor) ENUM(is)
This will not store anything else than two bare relations in the DB. However, they will behave differently and expose different information :
- the field "is" is a virtual enum and will contain the name of the relation.
- the field "data" will contain the relation data.
Relations are unidirectional and can only be modifed through the parent (or source) entity record, however sometimes it may be convenient for them to behave as if they were bidirectional.
That's why we introducted the RESERVE keyword. The REVERSE keyword allows the target entity record to contain a list of uids of the targeting entities.
You can see that forks are built on another notion : mutations. We will explicit this one later.
any field, relation or fork may be augmented with the MANDATORY keyword. A mandatory entry is, well, mandatory and any data creation or update resulting in a null or missing mandatory field will be rejected by the manager.
type: owner
relations:
assets: LIST(buildings) OWNER REVERSE(owner)
You will want to provide your entity with a description :
A person with two observables :
type: person
fields:
lastName: STRING
firstName: STRING
birthDate: DATE
mail: STRING
phone: STRING
hobbies: STRING SET
relations:
lover: REF(person)
friends: LIST(person)
observables:
self:
fields:
- lastName
- firstName
- birthDate
- mail
- phone
- hobbies
includes:
lover: other
friends: other
others:
fields:
- lastName
- firstName
- mail
An observable is a view through which you will be accessing stored data. You can use observable to manage level of access to data, like in this example.
The includes section is composed of pairs of key/value. the keys are relations to be followed and values are the observable that will be used to access the target entity data.
As the "self" observable is a strict representation of the entity, there is in fact no necessity to rewrite all the fields names. Instead, you can use the transparent keyword :
observables:
self:
transparent: true
includes:
lover: other
friends: other
This will provides all the fields to the observable.
CRUD operations on data, basic API
Record creation :
db.person.create({
lastName: "Smith",
firstName: "Lauren",
birthdate: "1993-04-12",
mail: "lauren.smith@example.com",
//We can omit fields
})
Research :
let [uid, ...stuff] = await db.person.find({
lastName: "Smith",
firstName: "Lauren"
})
//returns a list of uuids
Selection :
//return the first record matching
let res = await db.person.select(uid)
//return a list of records
res = await db.person.select([uid])
Update :
res = await db.person.update({
uid,
hobbies: ["football", "videogames"]
})
Delete :
res = await da.person.delete(uid)
Most of these can take either an uid, or an array of uids.
Others methods
Paginated selection :
- number of entities to fetch
- offset
- columns to queries
- order by a columns
db.person.page(number, offset, colums, orderby)
db.person.count(whereObject)
You will rarely use count, select, or find requests directly but most of the time rely on the observer/observables API. For the user, update and delete are the most important.
Observers
Observers are the main way to get data from the database.
Consider this entity schema :
type: person
fields:
lastName: STRING
firstName: STRING
birthDate: DATE
mail: STRING
phone: STRING
hobbies: STRING SET
relations:
lover: REF(person)
friends: LIST(person)
When we build a social web application, one of the use cases will be the possibility for users to visualize and make change to their personal data. Furthermore, others users will be able to access basic informations of other users.
So we define two observables in the schema corresponding to these data templates :
observables:
self:
fields:
- lastName
- firstName
- birthDate
- mail
- phone
- hobbies
includes:
lover: other
friends: other
others:
fields:
- lastName
- firstName
- mail
As you can see, in the observables declaration, you will specify which fields and relationship are readable through this specific observable.
In includes, you may map each relation (or reverse key) to the target (or source for reverse) entity desired observable.
To access these, we need to define a so-called observer :
const selfObs = new Observer({
name: "self",
state: (obs, uids) => db.getState(obs, uids),
select: (obs, uids) => db[obs.entity.type].select(uids, obs.filters),
observable: manager.model.findObs("self")
})
As you can see in this previous example, in order to define an observer, we need to provide it with a name, the observable to watch, and two functions.
State is the function used to retrieve both uids and timestamp of last update of the entity viewed through the observable.
Select is the function used to retrieve the associated data.
We have to explicitely define these functions because observers are designed to be able to communicate with the manager through inter-process communication or a network (like in a client/server application). Therefore, you will sometimes use them through websockets or your microservices framework remote call system.
This step accomplished, we can now use our observer to retrieve data. The first step is to watch one record of the desired entity type.
let res = await selfObs.watch(uid)
The watch function will return a format common to all observers output : an object with several properties :
- name : name of the observer
- emitter : name of the event emitter
- index : the index of all watched entities
- data : entities data
index and data are sharing the same object entries format :
[ entityType, [uid, object] ]
The output is provided as entries and not as a map of maps because we want it to be serialized and properly piped through whatever communication channel you are using.
As very sympathic people, we provides you with the Observer static method deserialize(event) that bring back the data to a proper nested maps format.
Explorers
Observer themselves are really dump things and only store flat data, each entity at the same level without any consideration nor easy way to retrieve entity relation.
Most of the time, you will still need to access data from multiple entities linked by relations. To address this matter, we built a tool called "explorers".
Explorers allow you to easily explore the data graph by automagically following the relationships between entities. You will need to statically build them from your model in your project.
import Explorer from "explorers.js"
Then you will need to show them how to retrieve data from the observers.
selectType = type => obs.get(type)
const explorer = Explorer(selectType)
Then you will simply be able to chain entities and retrieves field and even the raw record if necessary.
const me = explorer.user(myUid)
const myLover = me.lover
const myfriends = my.friends
//get the uids of the friends of my friends
me.myfriends.map(f => f.friends.map(ff => ff.uid))
//get raw data from a record
const myData = me._data
Designing data access model with the observer/observable design pattern
Defining multiple observables and observables graph is a good way to manage read access right. In our application following the example model in the above, each user will have an associated observer client-side, allowing it to see all the data he need, but not much more.
When you need to update or create new data from the client, you will make traditional REST API calls.