带有自定义 JS 的 ArangoDB

ArangoDB with custom JS

你好,请问有什么方法可以使用ArangoDB内置的JS环境来执行自定义JS吗?我想设置我的 JS 文件的路径,而不是 foxx 应用程序文件。

是的,这可以用 User Actions 来完成。 Foxx 被创建为更舒适的替代方案,并且可能是重要应用程序的更好选择。文档可能令人生畏,但 Foxx 服务实际上可以非常轻量级和简单(请参阅我的其他答案)。如果您真的不想为此使用 Foxx,请按以下方法手动操作:

首先在_modules系统集合中创建一个虚拟模块:

var db = require('org/arangodb').db;
db._modules.save({
  path: '/db:/ownTest',
  content: `
    exports.do = function (req, res, options, next) {
      res.body = 'test';
      res.responseCode = 200;
      res.contentType = 'text/plain';
    };
  `
});

然后创建一个使用它的路由:

db._routing.save({
  url: '/ourtest', 
  action: {
    controller: 'db://ownTest'
  }
});

最后,告诉 ArangoDB 更新其路由缓存,以便它注意到新路由:

require('internal').reloadRouting();

如果你 install your JavaScript modulejs/common/js/server/ 目录你可以使用模块名称(例如 myOnDiskModule)而不是虚拟模块名称 "db://owntest"controller.

对于较小的模块,您可以使用 callback 而不是 controller:

定义内联函数
db._routing.save({ 
  url: '/hello/echo',
  action: { 
    callback: `
      function (req, res) {
        res.statusCode = 200;
        res.body = require('js-yaml').safeDump({
          Hello: 'World',
          are: 'you here?'
        });
      }
    `
  } 
});

记住在更改路由集合后始终更新路由缓存:

require('internal').reloadRouting();

注意:2.8 中的 callback 实现有一个错误,将在 2.8.3 中修复。如果您想手动应用修复程序,它位于 commit b714dc5.

通过 GitHub:https://github.com/arangodb/arangodb/issues/1723#issuecomment-183289699

You are correct that modules are cached independently of the routing cache. Clearing the module cache (or preventing a module from being cached) is currently not supported.

The actions mechanism is really only intended as an internal API and only supported for backwards compatibility with early ArangoDB versions and some edge cases.

As you may have noticed while digging through the ArangoDB source code, Foxx provides a per-service module cache which is cleared whenever a Foxx service is reloaded. I would strongly encourage you to see whether Foxx fits your use case before continuing to dig into the actions mechanism.

It's actually possible to create a Foxx service with just two files (a manifest and a controller file) and without using repositories or models (you can just use the same APIs available in actions).

You just need a controller file like this (e.g. ctrl.js):

'use strict';
const Foxx = require('org/arangodb/foxx');
const ctrl = new Foxx.Controller(applicationContext);
ctrl.get('/', function (req, res) {
  res.send('Hello World');
});

with a manifest.json like this:

{
  "name": "my-foxx",
  "version": "0.0.0",
  "controllers": "ctrl.js",
  "defaultDocument": "",
  "engines": {"arangodb": "^2.8.0"}
}

You can then mount the service (upload a zip bundle) at a path like /db and access it:

curl http://localhost:8529/_db/_system/db

The upcoming 3.0 release will remove a lot of the existing conceptual overhead of Foxx which will hopefully make it even easier to get started with it.