Reference

Configuration

The below are the properties of the JSON object that constitutes the server configuration. The root object is APIServerConfig. The headings also correspond to the names of structures in the source code of RapidRows (see model.go).

APIServerConfig

Property Type Description
version string, required Version indicates the version of the schema according to which the other fields in this structure should be interpreted. This is in the semver syntax (a trailing .0 or .0.0 may be omitted). This field is required, and validation will fail without it.
listen string Listen indicates the IP or IP:port for the server to bind to and listen on. If the IP is omitted, the server will bind to all interfaces. If port is omitted, it defaults to 8080. IP may be an IPv4 or IPv6 literal. Hostnames are not allowed. When specifying an IPv6 literal along with a port, enclose the IPv6 literal within square brackets. Examples: 127.0.0.1:8000, [02:42:04:e8:f7:33]:8080, :9000, 02:42:04:e8:f7:33, 0.0.0.0:8080
commonPrefix string CommonPrefix will be prefixed to each URI. If specified, must begin with a slash, and must not end with one. Path components can contain only A-Z, a-z, 0-9, _, . or -. Examples: /api/v1
cors object CORS specifies the Cross Object Resource Sharing configuration for the server. This is optional, but note that CORS headers will not be added if this is not configured (and therefore the APIs may not be callable from browsers). See the documentation of the CORS struct for more info.
compression boolean Compression enables the transparent use of gzip and deflate content encoding. Outgoing responses from the server will be automatically compressed using gzip or deflate if the client request indicates support for it. Applies to the server as a whole, cannot be turned on for individual URIs.
endpoints array Endpoints is a list of all URIs implemented using queries or script. See the documentation of Endpoint struct for more info. Optional.
streams array Streams is a list of all websocket or Server Sent Event URIs. See the documentation of Stream struct for more info. Optional.
jobs array Jobs is a list of all scheduled jobs. See the documentation of the Job struct for more info. Optional.
datasources array Datasources is a list of all PostgreSQL databases that can be referred to by endpoints, streams and jobs. All datasources listed here will be connected to on startup (unless it is explicitly marked as lazy).

Endpoint

Property Type Description
uri string, required URI denotes the path of the endpoint. The URI must start with a slash but not end with one. Path components must consists of A-Z, a-z, 0-9, _, . or -. If a path component is to serve as a parameter, it can be wrapped in curly brackets. URI is case-sensitive. Examples: /user/{userid}, /repos/{owner}/{repo}/commits See also APIServerConfig.CommonPrefix.
methods array Methods configures the endpoint to accept HTTP requests only of the specified methods. The value can be one of: GET, POST, PUT, PATCH or DELETE. If omitted, the endpoint will respond to any method.
params array Params is a list of parameters that will be accepted by this endpoint. For SQL queries, the parameters will be made available as the bind variables $1, $2 etc. For javascript, the parameters will be accessible as an object $sys.params, with properties as parameter names. See the documentation for Param struct for more info.
impltype string, required ImplType is one of query-json, query-csv, exec, static-text, static-json or javascript, and must be specified. For query-json, query-csv and exec, the Script field should be a valid SQL statement. For static-json the Script should be valid JSON. For javascript, the Script should contain the javascript code.
datasource string Datasource refers to one of the datasources listed in APIServerConfig.Datasources. This field must be filled in for ImplType of query-json, query-csv and exec. Ignored for other types.
script string Script must be a valid SQL statement for query-json, query-csv or exec. For static-text, it will hold plain text. For static-json this must be valid JSON. For javascript, this should contain the javascript code. For type exec and no params, multiple SQL statements are allowed.
tx object TxOptions allows running of query-json, query-csv and exec types within a transaction. Ignored for other types. See the documentation of TxOptions struct for more info.
debug boolean Debug enables debug logging of all invocations of this endpoint.
timeout number Timeout in seconds for query-* and exec type. Ingored for other types. Ignored if <= 0.
cache number Cache the result for these many seconds. The APIServer should be started with a RuntimeInterface that supports caching for this to work. The cache entry is specific to the exact values of parameters for the invocation. Ignored if <= 0.

TxOptions

Property Type Description
access string Access is one of read only or read write (case insensitive). If omitted, defaults to read write.
level string ISOLevel is one of serializable, repeatable read or read committed (case insensitive). If omitted, defaults to read comitted.
deferrable boolean Deferrable turns on the deferrable option for the transaction.

Param

Property Type Description
name string, required Name is the name of the parameter, and is required. It has to be a C-like identifier (first character A-Z, a-z; optionally followed by A-Z, a-z, 0-9 or _.)
in string, required In specifies how the parameter will be passed, and is required. Must be one of query, path or body. If body is specified, the parameter maybe passed either as a form (application/x-www-form-urlencoded) or a json object (application/json).
required boolean, required Required indicates that the parameter, if not supplied, will be an error (the server will return a HTTP status code 400). If it is not required and not supplied, the SQL queries will receive a NULL as the value of this parameter.
type string, required Type of the parameter, required. Must be one of integer, number, string, boolean or array. If the type is number, the value can either be an integer or a float. If it is an array, the type of the elements of the array have to be specified using the .ElemType field.
enum array Enum can be used to specify a list of allowed values, only for types string or integer or number. Note that if an enum is specified, other types of validation (like mininum or maxLength) do not have any effect.
minimum number Minimum can be used to set the minimum allowed value for types integer or number.
maximum number Maximum can be used to set the maximum allowed value for types integer or number.
maxLength object MaxLength can be used to set the maximum length for values of type string.
pattern string Pattern is a regular expression that can be used for values of type string. If set, the supplied parameter value should match this regular expression. The regex syntax is RE2, most ES6 regexs should work.
minItems object MinItems can be used to set the minimum number of elements for arrays.
maxItems object MaxItems can be used to set the maximum number of elements for arrays.
elemType string ElemType specifies the type of individual elements if the Type field is array. It is required for array type parameters. It must be one of integer, number, string or boolean. Elements of varying types and nested arrays are not allowed.

Stream

Property Type Description
uri string, required URI denotes the path of the endpoint. The URI must start with a slash but not end with one. Path components must consists of A-Z, a-z, 0-9, _, . or -. If a path component is to serve as a parameter, it can be wrapped in curly brackets. URI is case-sensitive. Examples: /user/{userid}, /repos/{owner}/{repo}/commits See also APIServerConfig.CommonPrefix.
type string, required Type is one of “websocket” or “sse”, and is required.
channel string, required Channel referes to the name of the PostgreSQL channel. Must be a valid channel name, and must be specified.
datasource string, required Datasource is the name of the datasource listed in APIServerConfig.Datasources. The channel specified above will refer to a channel in this database.
debug boolean Debug enables debug logging of all invocations of this endpoint.

CORS

Property Type Description
allowedOrigins array AllowedOrigins is a list of origins a cross-domain request can be executed from. If the special * value is present in the list, all origins will be allowed. An origin may contain a wildcard () to replace 0 or more characters (i.e.: http://.domain.com). Only one wildcard can be used per origin. Default value is [*].
allowedMethods array AllowedMethods is a list of methods the client is allowed to use with cross-domain requests. Default value is [HEAD, GET, POST].
allowedHeaders array AllowedHeaders is list of non simple headers the client is allowed to use with cross-domain requests. If the special * value is present in the list, all headers will be allowed. Default value is [] but Origin is always appended to the list.
exposedHeaders array ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.
allowCredentials boolean AllowCredentials indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates.
maxAge object MaxAge indicates how long (in seconds) the results of a preflight request can be cached without sending another preflight request.
debug boolean Debug enables logging of CORS-related decisions for every endpoint.

Datasource

Property Type Description
name string, required Name uniquely identifies a datasource, and must be specified. It is of the format of a fully qualified domain name. Examples: prod-us-east-1, pgsrv03.acme.com
host string Host is an IP, a hostname or a Unix socket path to the listening Postgres server. Can include :port suffix to override the default port of 5432. Can include multiple comma-separated hosts.
dbname string Database is the name of the Postgres database to connect to. If omitted, will default to the name of the system user the server is running as.
user string User is the PostgreSQL user name to connect as. Defaults to be the same as the operating system name of the user running the application.
password string Password to be used if the server demands password authentication. This is in plain text, and is preferrable to use a Passfile instead.
passfile string Passfile pecifies the name of the file used to store passwords. See https://www.postgresql.org/docs/current/libpq-pgpass.html.
sslmode string SSLMode is one of disable, allow, prefer, require, verify-ca or verify-full. See PostgreSQL docs for more details.
sslcert string SSLCert specifies the file name of the client SSL certificate, replacing the default ~/.postgresql/postgresql.crt. This parameter is ignored if an SSL connection is not made.
sslkey string SSLKey specifies the location for the secret key used for the client certificate, to be used instead of ~/.postgresql/postgresql.key.
sslrootcert string SSLRootCert specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server’s certificate will be verified to be signed by one of these authorities. The default is ~/.postgresql/root.crt.
params object Params specified additional connection parameters, like application_name or search_path.
simple boolean PreferSimpleProtocol disables implicit prepared statement usage. Set this to true if you are connecting to a connection pooler that requires the use of PostgreSQL simple protocol.
timeout number Timeout specifies a timeout for establishing the connection, in seconds. Ignored if <= 0.
role string Role specifies a PostgreSQL role that will be set immediately upon connection. If set, must be a valid PostgreSQL role in the database.
pool object Pool configures the connection pooling parameters for this datasource. If no pool is configured for this datasource, connections to the PostgreSQL server are made as and when necessary without restraint.

ConnPool

Property Type Description
minConns integer MinConns sets the minimum number of connections in the pool. If specified, must be > 0.
maxConns integer MaxConns sets the maximum number of connections to the database that will be established. Defaults to max(4, number-of-CPUs). If specified, must be > 0.
maxIdleTime number MaxIdleTime in seconds is the duration after which an idle connection will be automatically closed. If specified, must be > 0.
maxConnectedTime number MaxConnectedTime in seconds is the duration since creation after which a connection will be automatically closed. If specified, must be > 0.
lazy boolean Lazy if set means that the connections will be established only on first demand and not at server startup.

Job

Property Type Description
name string, required Name uniquely identifies a job, and must be specified. It is of the format of a fully qualified domain name. Examples: mkparts.daily, proj3-weekly-reports
type string, required Type is one of exec or javascript, and must be specified. If the type is exec, then a Datasource and Script must also be specified. In case of javascript, the Script field must contain the javascript code.
schedule string, required Schedule is the CRON-style 5-part schedule for the job. Additionally, strings like @every 5m are also accepted. See the main documentation for more details. Examples: 0 12 * * 1, 23 0-20/2 * * *, @every 30m
datasource string Datasource refers to one of the datasources listed in APIServerConfig.Datasources. This field must be filled in for type exec.
script string, required Script is either the SQL statements (in case of exec) or the javascript code (in case of javascript). Either way, it must be specified and cannot be empty.
tx object TxOptions allows running of SQL statements (when type is exec) within a transaction. See the documentation of TxOptions struct for more info.
debug boolean Debug enables debug logging of all invocations of this job.
timeout number Timeout if set, specifies a timeout in seconds for the running of SQL statements specified for exec type jobs. Ignored for other types. Ignored if <= 0.

JavaScript API

The JavaScript environment presented to endpoint and scheduled job scripts is ES2020-compliant and contains all the global objects as per the spec. In addition, it contains a global objected called $sys, which has the following properties:

Property Type Description
params object An object whose keys are the endpoints’ parameter names. The values are the validated values supplied by the HTTP client. This object is present only for endpoint scripts.
result object or string Uninitialized upon entry. The script can set this to an object or a string. If an object is set, it is serialized to JSON and returned as an application/json HTTP response. If a string is set, it is returned as an text/plain HTTP response. If the value remains uninitialized, or is set to null or undefined, a 204 HTTP response without any content is returned.
acquire(datasource[, timeout]) function This function acquires a connection the specified datasource, optionally waiting only upto the specified timeout for the operation to complete. If successful, returns a connection object with properties listed below. On failure, it throws an error.

Properties of the connection object:

Property Type Description
query(sql, ...args) function This function performs a SQL query with the specified bind parameter values and returns an object with the resultset. See below for the properties of this object. On failure, it throws an error.
exec(sql, ...args) function This function performs a SQL query with the specified bind parameter values and returns an object indicating the number of rows affected. See below for the properties of this object. On failure, it throws an error.

Properties of the object returned by the query function:

Property Type Description
rows array Any array that contains one item for each row in the query result. Each item in turn is an array with as many items as there are columns in the query’s SELECT.

Properties of the object returned by the exec function:

Property Type Description
rowsAffected integer An integer indicating the number of rows affected by the query.

Error Handling in JavaScript

The functions acquire, query and exec throw Error objects on failure. The can be caught with try .. catch. Any uncaught exception, including ones thrown directly by the script, results in RapidRows returning a 500 HTTP response.

Even on errors the value of $sys.result will be checked and returned if set.

Go API

The Go package of RapidRows, github.com/rapidloop/rapidrows has public APIs that you can use. They are documented here.

© RapidLoop 2022. All rights reserved. This page was last updated 27 Sep 22 04:22 UTC.