How to access a database from Yate's Javascript module
Javascript module uses the connections to the database defined in Yate.
To make a query you must instantiate a database message type.
Using the examples below you will learn how to:
- retrieve information from database
- route calls to the result obtained from database
Contents |
Configure script in Javascript module
To configure a routing script you have to list it in the javascript.conf file.
In section [general] the parameter routing contains the name of the script.
The path to the file is set in parameter scripts_dir.If not set the default is been used 'share/scripts'.
If you need to set other javascript files then use [scripts] section or use #include to include other scripts.
[general] routing=example.js
Configure database account
You can set connection between Yate and MySQL database or Yate and PostGreSQL database module depending on your preference.
Note First you must check if module that you will use is loaded. If not, install devel packages.
The easiest way to check this, is from rmanager to write command status and to see if module name is listed there.
If you want to use MySQL the configuration file is mysqldb.conf and for PostgreSQL the configuration file is pgsqldb.conf.
Let's set account 'yateadmin' in mysqldb.conf, so we can use it in our examples:
[yateadmin] database=yateadmin user=mysql password=yate
Then in MySQL, the database and the tables must be created:
- create database yateadmin;
- create table lines (location varchar(255));
Database Examples
This is the example.js script.
By default your script should be in share/scripts directory from Yate sources.
To make a query, you have to send a database message.
Specify the connection to use by setting in parameter m.account the name of the database created in mysqldb.conf.
Retrieve information from database
// Get DB Object var m = new Message("database"); // Specify connection to use m.account = "yateadmin"; // Define Query m.query = "SELECT * FROM lines WHERE location IS NOT NULL ORDER BY line LIMIT 5"; // Run the Query if (m.dispatch()) { if (m.rows > 0) { Engine.output("Got " + m.rows + " records of " + m.columns + " fields"); Engine.output("result[0,0] = " + m.getResult(0,0)); var res = m.getColumn("location"); for (var i = 0; i < res.length; i++) { Engine.output("location[" + i + "] = " + res[i]); } } } else { Engine.output("Query failed"); }
Example with call interaction
// Get DB Object, Account, Query var m = new Message("database"); m.account = "yateadmin"; m.query = "SELECT location from lines where line = 'message.called'"; // Run the Query if (m.dispatch()) { Engine.output("Query Ok"); if (m.rows > 0) { Engine.output("result[0,0] = " + m.getResult(0,0)); // assuming m.getResult(0,0) returns "tone/busy" or "sip/sip:345@10.11.12.13" Channel.callJust(m.getResult(0,0)); } }
See also