node.jscordovaionic-frameworksails.js

How to Implement SailsJS + Phonegap / Cordova application


Already reviewed: How to make a phonegap mobile app from SailsJS and SailsJS to Phonegap?, but did not find the real answer. I would like to implement a project where the backend is SailsJS and the frontends are: 1) Web client; 2) PhoneGap client;

I looked at https://github.com/coderaven/sails-docs/blob/master/What-Is-Sails.md where the usage from PhoneGap / Cordova had been mentioned but, again - not a real example provided.

So I would appreciate if somebody could share a boilerplate example including Sails and PhoneGap/Cordova or at least to share some sample code.


Solution

  • After spending couple of days for research and trials / fails, let me share the solution that works for me. I will split my answer in two parts:

    1. SailsJS

    2. PhoneGap / Cordova

      • Create you PhoneGap project. It will produce www folder inside you PhoneGap project folder.
      • Find you www folder in your current sails project (see point 1) and just copy its content inside your PhoneGap www folder.
      • Open www/index.html file and add the code below before closing body tag:

          (function onLoad() {
            var io;
        
            Object.defineProperty(window, 'io', {
                get: function get() {
                    return io;
                },
                set: function set(value) {
                    var sails;
        
                    io = value;
                    // Immediately start connecting
                    var socket = io.connect(backendURL);
        
                    console.log('Connecting Socket.io to Sails.js...');
        
                    // Attach a listener which fires when a connection is established:
                    socket.on('connect', function socketConnected() {
        
                        console.log('Socket is now connected and globally accessible as `socket`.\n');
        
        
                        // set additional socket listeners here
                    });
        
        
                    Object.defineProperty(io, 'sails', {
                        get: function get() {
                            return sails;
                        },
                        set: function set(value) {
                            sails = value;
        
                            sails.url = 'backendUrl';
                        }
                    });
                }
            });
          })();
        

    of course, do not forget to enclose it in <script> tag and set proper value for backendUrl - this is your SailsJS URL.