diff --git a/package-lock.json b/package-lock.json index 3ed43bb..7b75e79 100644 --- a/package-lock.json +++ b/package-lock.json @@ -222,6 +222,11 @@ "supports-color": "5.4.0" } }, + "mock-fs": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/mock-fs/-/mock-fs-4.7.0.tgz", + "integrity": "sha512-WlQNtUlzMRpvLHf8dqeUmNqfdPjGY29KrJF50Ldb4AcL+vQeR8QH3wQcFMgrhTwb1gHjZn9xggho+84tBskLgA==" + }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", diff --git a/package.json b/package.json index 116a4a9..e648dbf 100644 --- a/package.json +++ b/package.json @@ -34,5 +34,8 @@ "devDependencies": { "assert-diff": "2.0.3", "mocha": "5.2.0" + }, + "dependencies": { + "mock-fs": "^4.7.0" } } diff --git a/test.js b/test.js index 0e2ae89..06ff280 100644 --- a/test.js +++ b/test.js @@ -1,5 +1,6 @@ var yesql = require('./yesql.js') var assert = require('assert-diff') +var mockFs = require('mock-fs'); it('pg', function() { assert.deepEqual( @@ -52,3 +53,16 @@ it('raw from file', function() { var sql = yesql('./') assert.equal(sql.updatePokemon, '-- updatePokemon\nUPDATE pokemon SET price=:price;\n') }) + +it('parses files from a directory without trailing slash', function() { + mockFs({ + './sqls': { + 'one.sql': '-- updatePokemon\nUPDATE pokemon SET price=$1;\n', + 'two.sql': '-- updateTransformer\nUPDATE transformer SET price=$1;\n' + } + }) + + var sql = yesql('./sqls') + + mockFs.restore() +}) diff --git a/yesql.js b/yesql.js index 945f2e1..5255c3f 100644 --- a/yesql.js +++ b/yesql.js @@ -1,27 +1,28 @@ var fs = require('fs') +var path = require('path') module.exports = function readSqlFiles(dir, options) { - var opts = options ? options : {pg: false} - return fs.readdirSync(dir).filter(function(file) { - return file.endsWith('.sql') - }).map(function(file) { - return { - name: file, - content: fs - .readFileSync(dir + file, 'utf8') - .replace(/\r\n/g, '\n') - } - }).reduce(function(acc, value) { - acc[value.name] = value.content - value.content.split('\n\n').forEach(function(sql) { - if (sql.startsWith('-- ')) { - var sqlName = sql.split('\n')[0].substring(2).trim() - acc[sqlName] = opts.type ? module.exports[opts.type](sql) : sql + var opts = options ? options : {pg: false} + return fs.readdirSync(dir).filter(function(file) { + return file.endsWith('.sql') + }).map(function(file) { + return { + name: file, + content: fs + .readFileSync(path.resolve(dir, file), 'utf8') + .replace(/\r\n/g, '\n') } - }) - return acc - }, {}) -} + }).reduce(function(acc, value) { + acc[value.name] = value.content + value.content.split('\n\n').forEach(function(sql) { + if (sql.startsWith('-- ')) { + var sqlName = sql.split('\n')[0].substring(2).trim() + acc[sqlName] = opts.type ? module.exports[opts.type](sql) : sql + } + }) + return acc + }, {}) + } module.exports.pg = pg module.exports.mysql = mysql