Skip to content

Instantly share code, notes, and snippets.

@cwilby
Last active February 16, 2018 00:07
Show Gist options
  • Save cwilby/335615d2c6e2886bd5b21be327c543e5 to your computer and use it in GitHub Desktop.
Save cwilby/335615d2c6e2886bd5b21be327c543e5 to your computer and use it in GitHub Desktop.
Loopback Remote Method

Problem

Given models A and B (where A has many B), what is the most performant way to accomplish the following with Loopback?

* Create A
* Create B
* Add B to A

Solution A - Remote Method

$ lb init
$ lb model A
...
$ lb model B
...
$ lb relation
# configure A to have many B

common/models/A.js

'use strict';

module.exports = function(A) {
    A.createAWithB = function({ a, b }, cb) {
        const { B } = A.app.models;

        A.create(a, (err, a) => {
            if(err) return cb('Error creating A in createAWithB');

            B.create(Object.assign({}, b, { aId: a.id }), (err, b) => {
                if(err) return cb('Error creating B in createAWithB');

                cb(null, a);
            });
        });
    };

    A.remoteMethod(
        'createAWithB', {
            http: {
                path: '/createAWithB',
                verb: 'post'
            },
            accepts: {
                arg: 'vm',
                type: 'Object',
                http: {
                    source: 'body'
                }
            },
            returns: {
                arg: 'a',
                type: 'Object'
            }
        }
    );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment