0
votes

I am creating a cordova application with loopback offline sync using sqlite as its datasource. Here is my code:

lbclient\datasources.json:

{
 "remote": {
    "connector": "remote"
},
 "sqlite": {
    "connector": "sqlite",
    "location": "default",
    "file_name": "sqlite.sqlite3",
    "debug": false
  }
}

lbclient\lbclient.js:

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var client = module.exports = loopback();

if (client.connectorRegistry) {
   console.log(client.connectorRegistry);
}
client.connector('sqlite', require('loopback-connector-cordova-sqlite'));

boot(client);

On my browser.bundle.js, I noticed that the try block is executed twice

app.dataSource = function(name, config) {
  try {
    var ds = dataSourcesFromConfig(name, config, this.connectors, this.registry);
    this.dataSources[name] =
    this.dataSources[classify(name)] =
    this.dataSources[camelize(name)] = ds;
    ds.app = this;
    return ds;
  } catch (err) {
    if (err.message) {
    err.message = g.f('Cannot create data source %s: %s',
    JSON.stringify(name), err.message);
  }
    throw err;
  }
};

Here's the dataSourcesFromConfig:

function dataSourcesFromConfig(name, config, connectorRegistry, registry) {
  var connectorPath;

  assert(typeof config === 'object',
  'can not create data source without config object');

  if (typeof config.connector === 'string') {
     name = config.connector;
     if (connectorRegistry[name]) {
        config.connector = connectorRegistry[name];
     } else {
        connectorPath = path.join(__dirname, 'connectors', name + '.js');

        if (fs.existsSync(connectorPath)) {
          config.connector = require(connectorPath);
        }
     }
    if (config.connector && typeof config.connector === 'object' && !config.connector.name)
        config.connector.name = name;
    }

   return registry.createDataSource(config);
 }

On the first run of dataSourcesFromConfig, the db (sqlite) is initialized just fine but on the second run, I now get the error:

browser.bundle.js:93172 Uncaught TypeError: Cannot create data source "sqlite": fs.existsSync is not a function

Why am I encountering that? Can you please help me. Thank you so much.

1

1 Answers

0
votes

You have to require the connector, otherwise browserify does not know that it needs to be included in the final bundle. Do it programmatically, you can inline require sqlite connector and then use attachTo on every model you want to use with sqlite. In boot script for example:

const DataSource = require("loopback-datasource.juggler").Datasource    

module.exports = (app) => {

   const local = new Datasource({
        file_name:"dev.sqlite3",
        location: "default",
        name: "local",
        connector: require("loopback-connector-cordova-sqlite")
    })

    app.models["myModel"].attachTo(local)
}