Back to top
  Back to overview

Embedded scripting functions

SurrealDB allows for advanced functions with complicated logic, by allowing embedded functions to be written in JavaScript. These functions support the ES2020 JavaScript specification.

Simple functions

Embedded JavaScript functions within SurrealDB support all functionality in the ES2020 specification including async / await functions, and generator functions. Any value from SurrealDB is converted into a JavaScript type automatically, and the return value from the JavaScript function is converted to a SurrealDB value.

CREATE person SET scores = function() {
	return [1,2,3].map(v => v * 10);
};

Function context

The this context of each embedded function is automatically set to the current document on every invocation. This allows the function to access the properties and fields of the current record being accessed / modified.

CREATE film SET
	ratings = [
		{ rating: 6, user: user:bt8e39uh1ouhfm8ko8s0 },
		{ rating: 8, user: user:bsilfhu88j04rgs0ga70 },
	],
	featured = function() {
		return this.ratings.filter(r => {
			return r.rating >= 7;
		}).map(r => {
			return { ...r, rating: r.rating * 10 };
		});
	}
;

Function arguments

Additional arguments can be passed in to the function from SurrealDB, and these are accessible using the arguments object within the JavaScript function.

-- Create a new parameter
LET $value = "SurrealDB";
-- Create a new parameter
LET $words = ["awesome", "advanced", "cool"];
-- Pass the parameter values into the function
CREATE article SET summary = function($value, $words) {
	return `${arguments[0]} is ${arguments[1].join(', ')}`;
};

JavaScript types

Any value from SurrealDB is converted into a JavaScript type automatically, and the return value from the JavaScript function is converted to a SurrealDB value. Boolean values, Integers, Floats, Strings, Arrays, Objects, and Date objects are all converted automatically to and from SurrealDB values.

CREATE user:test SET created_at = function() {
	return new Date();
};

In addition a number of special classes are included within the JavaScript functions, for the additional types which are not built into JavaScript. These enable the creation of duration values, record values, and UUID values from within JavaScript.

CREATE user:test SET
	session_timeout = function() {
		return new Duration('1w');
	},
	best_friend = function() {
		return new Record('user', 'joanna');
	},
	identifier = function() {
		return new Uuid('03412258-988f-47cd-82db-549902cdaffe');
	}
;