DEV Community

BONNAURE Olivier
BONNAURE Olivier

Posted on

ArangoDB : The new Graal ? Part 3

After the authentification seen in part2, it's time to play with collections.
Here the main.js file.

'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);
Enter fullscreen mode Exit fullscreen mode

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

// 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();
});
Enter fullscreen mode Exit fullscreen mode

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

// 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.');
Enter fullscreen mode Exit fullscreen mode

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 to build administration apps based on Foxx, UIkit, RiotJS & Brunch. It will allow you to manage file upload, tags and more.

foxxy

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

Top comments (0)