Skip to content

Usage with express.js

Alexey Gordeyev edited this page Jan 1, 2016 · 1 revision

A minimal express application

$ mkdir example-app
$ cd example-app
$ npm install express express-generator
$ node_modules/.bin/express . -f
$ npm install
$ ./bin/www

Adding Caminte to the application

Now that we have the express application in place, we can start adding Caminte structure to it. What we need for that are the following packages: caminte, caminte-cli, sqlite3. Please note, that for the sake of simplicity this tutorial will use SQLite 3.

npm install --save caminte caminte-cli sqlite3

This will install the respective packages and uses the upcoming stable release of caminte. We can now let the caminte CLI initialize the project's directory:

$ node_modules/.bin/caminte --init -a sqlite3

Running this command will create the folders config, migrations and models, like that

.
| 
|-- models
|   `-- ...
|-- routes
|   `-- ...
|-- test
|   |-- model
|   |   `-- ...
|   |-- route
|   |   `-- ...
|   |-- unit
|   |   `-- ...
|   `-- tests.js
|-- models.js
`-- database.js

Implementing an app

As an example application we will create a very basic and simple todo tool, which allows the creation of users and the management of their tasks.

In order to create a maintainable application, we will put all the database logic into the models folder. When the application gets fired up, caminte will async the models with the database and afterwards start the server. This way we don't clutter the application while making use of caminte's features. Add the following strings in app.js.

var models = require('./models');
models.init(app);

All models of our application are located as separate files in the models folder. If you want to add a new model, just add it to this folder and everything will work automagically. Also you can use the caminte CLI's caminte --model name [fields], more details

Create model and routes

$ node_modules/.bin/caminte --crud User active:bool name email password note:text created:date

Will be create two files:

.
|-- models
|   `-- User.js
`-- routes
    `-- users.js

The file routes/users.js contains the logic for a request to load, create or delete the users from the database. Add the following string in app.js.

app.use('/users', require('./routes/users.js'));

Start App

$ SET AUTOUPDATE=1 & npm start