ArangoDB : The new Graal ? Part 3
Tags: arangodb, foxx, crud, javascript
Published: 2017-12-26 21:49:54

---
title: "ArangoDB : The new Graal ? Part 3"
published: true
description: CRUD
tags: arangodb, foxx, crud, javascript
---

After the authentification seen in [part2](https://dev.to/solisoft/arangodb--the-new-graal--part-2-6mc), it's time to play with collections.
Here the main.js file.

```js
'use strict';
// Define db & joi for db calls and validation
const db = require('@arangodb').db;
const joi = require('joi');
// Enable cache
require("@arangodb/aql/cache").properties({ mode: "on" });

// Create router and session storage
const createRouter = require('@arangodb/foxx/router');
const sessionsMiddleware = require('@arangodb/foxx/sessions');
const jwtStorage = require('@arangodb/foxx/sessions/storages/jwt');
const router = createRouter();
const sessions = sessionsMiddleware({
  storage: jwtStorage('something secret'),
  transport: 'header'
});


// Use sessions & router
module.context.use(sessions);
module.context.use(router);
```

If you want to protect your service to registered users only :

```js
// Use the authentification
module.context.use(function (req, res, next) {
  if(!req.session.uid) res.throw('unauthorized');
  res.setHeader("Access-Control-Expose-Headers", "X-Session-Id");
  next();
});
```

Ok, let's start writing CRUD stuff. In this sample I'll use the `posts` collection as sample.

```js
// GET /page/:page
router.get('/page/:page', function (req, res) {
  res.send({ data: db._query(`
    LET count = LENGTH(posts)
    LET data = (FOR doc IN posts SORT doc._key DESC LIMIT @offset,25 RETURN doc)
    RETURN { count: count, data: data }
    `, { "offset": (req.pathParams.page - 1) * 25}).toArray() });
})
.header('X-Session-Id')
.description('Returns all objects using pagination');

// GET /:id
router.get('/:id', function (req, res) {
  res.send(db.posts.document(req.pathParams.id));
})
.header('X-Session-Id')
.description('Returns object within ID');

// POST /
router.post('/', function (req, res) {
  var data = {
    field_1: req.body.field_1,
    field_2: req.body.field_2,
    field_3: req.body.field_3
  }
  res.send(db.posts.save(data));
})
.body(joi.object({
  field_1: joi.string().required(),
  field_2: joi.number().required(),
  field_3: joi.any(),
}), 'data')
.header('X-Session-Id')
.description('Create a new object.');

// PUT /:id
router.put('/:id', function (req, res) {
  var object = db.posts.document(req.pathParams.id)
  var data = {
    field_1: req.body.field_1,
    field_2: req.body.field_2,
    field_3: req.body.field_3
  }
  res.send(db.posts.update(object, data));
})
.body(joi.object({
  field_1: joi.string().required(),
  field_2: joi.number().required(),
  field_3: joi.any(),
}), 'data')
.header('X-Session-Id')
.description('Update an object.');

// DELETE /:id
router.delete('/:id', function (req, res) {
  res.send(db.posts.remove("posts/"+req.pathParams.id));
})
.header('X-Session-Id')
.description('delete an object.');
```

You have here a minimal but working sample of a complete CRUD using Foxx & ArangoDB.

To save my time, I built a very useful tool called [foxxy](https://foxxy.ovh) to build administration apps based on Foxx, UIkit, RiotJS & Brunch. It will allow you to manage file upload, tags and more.

![foxxy](https://foxxy.ovh/assets/foxxy.png)

You can now build any kind of Rest API which can be linked to any kind of client application.