Remote Objects API

Class: RemoteObjects(options)

Create a new RemoteObjects with the given options.

var remoteObjects = require('strong-remoting').create();
Arguments
Name Type Description
options Object
Class Properties
Name Type Description
auth Object

Authentication options used by underlying adapters to set authorization metadata. The rest adapter supports:

  • basic - username and password are required.
  • digest - username and password required and sendImmediately must be false.
  • bearer - bearer must be set as the bearer token
auth.username String
auth.password String
auth.bearer String

The bearer token.

auth.sendImmediately Boolean

Defaults to false.

Class: RemoteObjects Static Methods

RemoteObjects.defineType(name, converter)

Define a named type conversion. The conversion is used when a SharedMethod argument defines a type with the given name.

remotes.defineType('MyType', function(val, ctx) {
  // use the val and ctx objects to return the concrete value
  return new MyType(val);
});

Note: the alias remotes.convert() is deprecated.

Arguments
Name Type Description
name String

The type name

converter Function

Class: RemoteObjects Instance Methods

remoteObjects.adapter(name)

Get an adapter by name.

Arguments
Name Type Description
name String

The adapter name

remoteObjects.addClass(sharedClass)

Add a shared class.

Arguments
Name Type Description
sharedClass SharedClass

remoteObjects.after(methodMatch, hook)

Execute the given hook function after the matched method string.

Arguments
Name Type Description
methodMatch String

The glob to match a method string

hook Function
Callback
Name Type Description
ctx Context

The adapter specific context

next Function

Call with an optional error object

method SharedMethod

The SharedMethod object

Example

Do something after the speak instance method. NOTE: you cannot cancel a method after it has been called.

remotes.after('dog.prototype.speak', function(ctx, next) {
  console.log('After speak!');
  next();
});

Do something before all methods.

remotes.before('**', function(ctx, next, method) {
  console.log('Calling:', method.name);
  next();
});

Modify all returned values named result.

remotes.after('**', function(ctx, next) {
  ctx.result += '!!!';
  next();
});

remoteObjects.afterError(methodMatch, hook)

Execute the given hook function after the method matched by the method string failed.

Arguments
Name Type Description
methodMatch String

The glob to match a method string

hook Function
Callback
Name Type Description
ctx Context

The adapter specific context

next Function

Call with an optional error object

method SharedMethod

The SharedMethod object

Example

Do something after the speak instance method failed.

remotes.afterError('dog.prototype.speak', function(ctx, next) {
  console.log('Cannot speak!', ctx.error);
  next();
});

Do something before all methods:

remotes.afterError('**', function(ctx, next, method) {
  console.log('Failed', method.name, ctx.error);
  next();
});

Modify all returned errors:

remotes.after('**', function(ctx, next) {
  if (!ctx.error.details) ctx.result.details = {};
  ctx.error.details.info = 'intercepted by a hook';
  next();
});

Report a different error:

remotes.after('dog.prototype.speak', function(ctx, next) {
  console.error(ctx.error);
  next(new Error('See server console log for details.'));
});

remoteObjects.before(methodMatch, hook)

Execute the given function before the matched method string.

Arguments
Name Type Description
methodMatch String

The glob to match a method string

hook Function
Callback
Name Type Description
ctx Context

The adapter specific context

next Function

Call with an optional error object

method SharedMethod

The SharedMethod object

Example

Do something before the user.greet method is called:

remotes.before('user.greet', function(ctx, next) {
  if ((ctx.req.param('password') || '').toString() !== '1234') {
    next(new Error('Bad password!'));
  } else {
    next();
  }
});

Do something before any user method:

remotes.before('user.*', function(ctx, next) {
  console.log('Calling a user method.');
  next();
});

Do something before a dog instance method:

remotes.before('dog.prototype.*', function(ctx, next) {
  var dog = this;
  console.log('Calling a method on "%s".', dog.name);
  next();
});

remoteObjects.classes()

Get all classes.

remoteObjects.connect(url, name)

Create a connection to a remoting server.

Arguments
Name Type Description
url String

Server root

name String

Name of the adapter (eg. "rest")

remoteObjects.findMethod(methodString)

Find a method by its string name.

Arguments
Name Type Description
methodString String

String specifying the method. For example:

  • MyClass.prototype.myMethod
  • MyClass.staticMethod
  • obj.method

remoteObjects.handler(name, options)

Create a handler from the given adapter.

Arguments
Name Type Description
name String

Adapter name

options Object

Adapter options

remoteObjects.invoke(method, [ctorArgs], [args], [callback])

Invoke a method on a remote server using the connected adapter.

Arguments
Name Type Description
method String

The remote method string

[ctorArgs] String

Constructor arguments (for prototype methods)

[args] String

Method arguments

[callback] Function

callback

Callback
Name Type Description
err Error
arg... Any

remoteObjects.invokeMethodInContext(ctx, method, cb)

Invoke the given shared method using the supplied context. Execute registered before/after hooks.

Arguments
Name Type Description
ctx Object
method Object
cb function(Error|undefined)

remoteObjects.methods()

List all methods.

remoteObjects.toJSON()

Get as JSON.

Class: SharedClass(name, constructor, options)

Create a new SharedClass with the given options.

Arguments
Name Type Description
name String

The SharedClass name

constructor Function

The constructor the SharedClass represents

options Object

Additional options.

Class Properties
Name Type Description
ctor Function

The constructor

http Object

The HTTP settings

Class: SharedClass Static Methods

SharedClass.normalizeHttpPath()

Normalize HTTP path.

Class: SharedClass Instance Methods

sharedClass.defineMethod(name, [options])

Define a shared method with the given name.

Arguments
Name Type Description
name String

The method name

[options] Object

Set of options used to create a SharedMethod. See the full set of options

sharedClass.disableMethod(fn, isStatic)

Disable a sharedMethod with the given name or function object.

Arguments
Name Type Description
fn String

The function or method name

isStatic Boolean

Disable a static or prototype method

sharedClass.find(fn, [isStatic])

Find a sharedMethod with the given name or function object.

Arguments
Name Type Description
fn String or Function

The function or method name

[isStatic] Boolean

Required if fn is a String. Only find a static method with the given name.

Returns
Name Type Description
result SharedMethod

sharedClass.getKeyFromMethodNameAndTarget(fn, isStatic)

Get a key for the given method.

Arguments
Name Type Description
fn String

The function or method name.

isStatic Boolean

True if the method is static.

sharedClass.methods(options)

Get all shared methods belonging to this shared class.

Arguments
Name Type Description
options

{Object}

options.includeDisabled

{Boolean} include all methods, even disabled.

Returns
Name Type Description
result Array.<SharedMethod>

An array of shared methods

sharedClass.resolve(resolver)

Define a shared method resolver for dynamically defining methods.

Arguments
Name Type Description
resolver Function

The resolver function.

Example
// below is a simple example
sharedClass.resolve(function(define) {
  define('myMethod', {
    accepts: {arg: 'str', type: 'string'},
    returns: {arg: 'str', type: 'string'}
    errors: [ { code: 404, message: 'Not Found', responseModel: 'Error' } ]
  }, myMethod);
});
function myMethod(str, cb) {
  cb(null, str);
}

Class: SharedMethod(fn, name, sharedClass, options)

Create a new SharedMethod (remote method) with the given fn. See also Remote methods.

Arguments
Name Type Description
fn Function

The Function to be invoked when the method is invoked.

name String

The name of the SharedMethod.

sharedClass SharedClass

The SharedClass to which the method will be attached.

options Object

See below.

options
Name Type Description
[accepts] Array or Object

Defines either a single argument as an object or an ordered set of arguments as an array.

[accepts.arg] String

The name of the argument.

[accepts.description] String

Text description of the argument, used by API documentation generators like Swagger.

[accepts.http] String

HTTP mapping for the argument. See argument mapping in the docs.

[accepts.http.source] String

The HTTP source for the argument. May be one of the following:

  • req - the Express Request object.
  • res - the Express Response object.
  • body - the req.body value.
  • form - req.body[argumentName].
  • query - req.query[argumentName].
  • path - req.params[argumentName].
  • header - req.headers[argumentName].
  • context - the current HttpContext.
[accepts.rest] Object

The REST mapping / settings for the argument.

[accepts.type] String

Argument datatype; must be a Loopback type.

[aliases] Array

A list of aliases for the method.

[errors] Array or Object

Object or Array containing error definitions.

[http] Array

HTTP-only options.

[http.errorStatus] Number

Default error status code.

[http.path] String

HTTP path (relative to the model) at which the method is exposed.

[http.status] Number

Default status code when the callback is called without an error.

[http.verb] String

HTTP method (verb) at which the method is available. One of: get, post (default), put, del, or all

[isStatic] Boolean

Whether the method is a static method or a prototype method.

[returns] Array or Object

Specifies the remote method's callback arguments; either a single argument as an object or an ordered set of arguments as an array. The err argument is assumed; do not specify. NOTE: Can have the same properties as accepts, except for http.target.

[shared] Boolean

Whether the method is shared. Default is true.

[status] Number

The default status code.

Class Properties
Name Type Description
name String

The method name.

aliases Array.<String>

An array of method aliases.

isStatic Boolean

Whether the method is static; from options.isStatic. Default is true.

accepts Array or Object

See options.accepts.

returns Array or Object

See options.returns.

errors Array or Object

See options.errors.

description String

Text description of the method.

notes String

Additional notes, used by API documentation generators like Swagger.

http String
rest String
shared String
[documented] Boolean

Default: true. Set to false to exclude the method from Swagger metadata.

Class: SharedMethod Static Methods

coerceAccepts(uarg, desc)

Coerce an 'accepts' value into its final type. If using HTTP, some coercion is already done in http-context.

This should only do very simple coercion.

Arguments
Name Type Description
uarg

Argument value.

desc Object

Argument description.

SharedMethod.convertArg()

Returns a reformatted Object valid for consumption as remoting function arguments

convertToBasicRemotingType(type)

Returns an appropriate type based on a type specifier from remoting metadata.

Arguments
Name Type Description
type Object

A type specifier from remoting metadata, e.g. "[Number]" or "MyModel" from accepts[0].type.

Returns
Name Type Description
result String

A type name compatible with the values returned by SharedMethod.getType(), e.g. "string" or "array".

SharedMethod.fromFunction(fn, name, SharedClass, isStatic)

Create a new SharedMethod with the given fn. The function should include all the method options.

Arguments
Name Type Description
fn Function
name Function
SharedClass SharedClass
isStatic Boolean

SharedMethod.getType(val)

Returns an appropriate type based on val.

Arguments
Name Type Description
val

The value to determine the type for

Returns
Name Type Description
result String

The type name

SharedMethod.toResult()

Returns a reformatted Object valid for consumption as JSON from an Array of results from a remoting function, based on returns.

Class: SharedMethod Instance Methods

sharedMethod.addAlias(alias)

Add an alias

Arguments
Name Type Description
alias String

Alias method name.

sharedMethod.getFunction()

Get the function the SharedMethod will invoke().

sharedMethod.invoke(scope, args, remotingOptions, cb)

Execute the remote method using the given arg data.

Arguments
Name Type Description
scope Object

this parameter for the invocation

args Object

containing named argument data

remotingOptions Object

remote-objects options

cb Function

callback fn(err, result) containing named result data

sharedMethod.isDelegateFor(suspect)

Determine if this shared method invokes the given "suspect" function.

Arguments
Name Type Description
suspect String or Function

The name of the suspected function or a Function.

Returns
Name Type Description
result

Boolean True if the shared method invokes the given function; false otherwise.

Example
sharedMethod.isDelegateFor(myClass.myMethod); // pass a function
sharedMethod.isDelegateFor(myClass.prototype.myInstMethod);
sharedMethod.isDelegateFor('myMethod', true); // check for a static method by name
sharedMethod.isDelegateFor('myInstMethod', false); // instance method by name

Class: HttpContext(req, res, method, options)

Create a new HttpContext with the given options. Invoking a remote method via HTTP creates HttpContext object.

Arguments
Name Type Description
req Object

Express Request object.

res Object

Express Response object.

method Function

A SharedMethod

options Object

See below.

options
Name Type Description
xml Boolean

Set to true to enable XML-based types. Default is false.

Class: HttpContext Instance Methods

httpContext.buildArgs()

Build args object from the http context's req and res.

httpContext.done()

Finish the request and send the correct response.

httpContext.getArgByName(name, options)

Get an arg by name using the given options.

Arguments
Name Type Description
name String
options Object

optional

httpContext.invoke()

Invoke the given shared method using the provided scope against the current context.

Class: HttpInvocation(method, [args], base)

Create a new HttpInvocation.

Arguments
Name Type Description
method SharedMethod
[args] Array
base String

The base URL

Class Properties
Name Type Description
base String

The base URL

method SharedMethod

The SharedMethod which will be invoked

args Array

The arguments to be used when invoking the SharedMethod

Class: HttpInvocation Static Methods

inherits()

Inherit from EventEmitter.

HttpInvocation.isAcceptable()

Determine if the value matches the given accept definition.

Class: HttpInvocation Instance Methods

httpInvocation.createRequest()

Build args object from the http context's req and res.

httpInvocation.getArgByName(name)

Get an argument value by name.

Arguments
Name Type Description
name String
Returns
Name Type Description
result

Value of specified argument.

httpInvocation.getResponse()

Get Response object

httpInvocation.invoke()

Start the invocation.

httpInvocation.transformResponse(res, callback)

Transform the response into callback arguments

Arguments
Name Type Description
res HttpResponse
callback Function