Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sync vs Async initialisation #12

Open
oliverbrooks opened this issue Jun 28, 2016 · 4 comments
Open

Sync vs Async initialisation #12

oliverbrooks opened this issue Jun 28, 2016 · 4 comments
Milestone

Comments

@oliverbrooks
Copy link
Contributor

I'm wondering if it is easier to initialise sql-stamp by loading all the files synchronously.

For example:

var sqlStamp = require("sql-stamp");

// Make some templates
var templates = sqlStamp(["/path/to/sql"]); // This step sync

// Use those templates
var sql = templates("/path/to/sql", {
  one: "fish"
});

The advantage of this is you could easily put the template loading part into a module and require it.

/sql-templates.js

var sqlStamp = require("sql-stamp");

// Make some templates
module.exports = sqlStamp(["/path/to/sql"]); // This step sync

/model.js

var templates = require("./sql-templates");

// Use those templates
var sql = templates("/path/to/sql", {
  one: "fish"
});

// use sql

With async you need some kind of initialising step to ensure all the files are loaded.

/sql-templates.js

var sqlStamp = require("sql-stamp");

// Make some templates
var templates;
function init () {
  return sqlStamp(["/path/to/sql"]).then(function (sql) {
    templates = sql;
    return sql;
  });
}

module.exports = function () {
  if (templates) {
    return Promise.resolve(templates);
  } else {
    return init();
  }
}

/model.js

var templates = require("./sql-templates");

// Use those templates
templates().then(function (templates) {
  var sql = templates("/path/to/sql", {
    one: "fish"
  });
  // use sql
});

As files are loaded once on app start it would seem there is no performance reason to load async and seems more cumbersome to use.

Hopefully I've missed some easy way to initialise.

@orangemug
Copy link
Owner

@oliverbrooks I think you right, I think we can just add a .sync method to the API and use .readFileSync rather than .readFile here

return fs.readFileAsync(filepath)

@oliverbrooks
Copy link
Contributor Author

@orangemug that would do it.

So you propose that the API would be something like this?

var templates = sqlStamp.sync(["my/files"])

@orangemug
Copy link
Owner

Yup that seems to be convention used elsewhere

@orangemug
Copy link
Owner

FYI the API was originally designed to be used with glob so something like

var templates = sqlStamp.sync(glob.sync("./sql/**/*.sql"))

@orangemug orangemug added this to the v0.9.0 milestone Jul 6, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants