0

I'm trying to use my Sails.js models outside of the sails context. I have one simple model called "Request", and I'm using the sails-disk adapter. Everything works fine inside the Sails app, but when I try and use the model outside the app (I'm running a separate proxy server that needs to save requests passing through it) I get the error below. It seems that this.waterline.schema is undefined for some reason. This is triggered by the "new Request()" line in the last code example.

Note: This question suggests using Sails.load to wrap everything in the sails server context, but I already have a sails server running separately from the proxy server, so I get all sorts of errors when I try to do this.

Error:

/path-to-app/node_modules/sails/node_modules/waterline/lib/waterline/core/index.js:70
var schemaAttributes = this.waterline.schema[this.identity].attributes;

TypeError: Cannot read property 'request' of undefined

api/models/Request.js

module.exports = {
  identity: 'request',
  schema: true,
  autoCreatedAt: true,
  autoUpdatedAt: true,
  migrate: 'alter',
  attributes: {
    id: {
      type: 'string',
      primaryKey: true,
      required: true
    },

    method: 'string',
    url: 'string'
}

./proxy.js attempt to load sails waterline model in external script (abbreviated)

var uuid = require('node-uuid'),
  Waterline = require('sails/node_modules/waterline'),
  RequestCollection = require('./api/models/Request.js'),
  sailsDisk = require('sails-disk');

RequestCollection.adapter = 'localDiskDb';
var Request = Waterline.Collection.extend(RequestCollection);

new Request({
  adapters: {
    localDiskDb: sailsDisk
  }
}, function(err, collection) {
  if (err) {
    console.error(err);
    return;
  }

  // Save the request
  collection.create({
    id: uuid.v4(),
    method: 'foo method',
    url: 'foo url'
  }).exec();
});
Community
  • 1
  • 1
Marc
  • 3,812
  • 8
  • 37
  • 61

1 Answers1

0

You can run the sails server on a different port (as well as any other common non-duplicable resource ) to avoid errors

    var SailsApp = require('sails').Sails;
    var Sails = new SailsApp();
    process.env.NODE_ENV = "database";  //use a different environment settings file
    process.env.PORT = "1332";  //and a different port , blocked by firewall if needed

    Sails.lift({ 
        log: {
            //level: 'silly'
            level: 'silent'
        }, 
    }, function (err, sails) {
        if (err) {
            return done(err);
        }
        //do something with sails here.
    });
arkoak
  • 2,437
  • 21
  • 35
  • I wasn't even trying to run the sails server again though. I was doing a Sails.load, not Sails.lift. – Marc Feb 26 '15 at 19:50
  • sails.load can be used in place of sails.lift in the above code, you will not need to change the port in that case. `Sails.load(function(err, sails) { .. });` – arkoak Feb 27 '15 at 05:12