Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/tests/expected/get-sqlite-router/big-result.json
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ See `sqlite-to-rest --help` for more info.
const app = new require('koa')(),
dbPath = 'path/to/your/db.sqlite3'

getSqliteRouter({ dbPath }).then(router => {
getSqliteRouter({ dbPath }).then((router) => {
app.use(router.routes())
// ...
})
Expand Down
5 changes: 4 additions & 1 deletion bin/sqlite-to-rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
const structuredCli = require('structured-cli'),
fp = require('lodash/fp'),
requireDir = require('require-dir'),
state = require('../lib/services/state')
state = require('../lib/services/state'),
pjson = require('../package.json')

//------//
// Init //
//------//
Expand All @@ -24,4 +26,5 @@ structuredCli.create({
'A collection of tools exposing the sqlite-to-rest functionality' +
' via cli. All commands here are also exposed on the required object.',
commands: fp.values(requireDir('../cli/commands')),
version: pjson.version,
})
4 changes: 2 additions & 2 deletions cli/commands/generate-skeleton.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const common = require('../../lib/common'),
// Init //
//------//

const isSqliteFileSync = common.isSqliteFileSync
const isSqlite3FileSync = common.isSqlite3FileSync

//------//
// Main //
Expand All @@ -23,7 +23,7 @@ const command = {
marg: {
dbPath: {
flags: ['require'],
custom: { isFile: isSqliteFileSync },
custom: { isSqlite3File: isSqlite3FileSync },
},
},
args: [
Expand Down
14 changes: 7 additions & 7 deletions lib/api/get-sqlite-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const bPromise = require('bluebird'),
dbSchema = require('./services/db-schema'),
fp = require('lodash/fp'),
getSchema = require('./helpers/get-schema'),
koaBodyparser = require('koa-bodyparser'),
{ bodyParser: koaBodyparser } = require('@koa/bodyparser'),
koaDecodedQuerystring = require('koa-decoded-querystring'),
KoaRouter = require('koa-router'),
madonnaFn = require('madonna-function'),
Expand All @@ -26,7 +26,7 @@ bPromise.promisifyAll(sqlite3.Database.prototype)

const createMadonnaFunction = madonnaFn.create,
forEachWithKey = utils.forEachWithKey,
isSqliteFileSync = common.isSqliteFileSync,
isSqlite3FileSync = common.isSqlite3FileSync,
routeBuilders = requireDir('./helpers/route-builders', { recurse: true })

//------//
Expand All @@ -38,7 +38,7 @@ const mGetSqliteRouter = createMadonnaFunction({
schema: {
dbPath: {
flags: ['require'],
custom: { isSqlitePath: isSqliteFileSync },
custom: { isSqlite3File: isSqlite3FileSync },
},
config: ['isLadenPlainObject'],
},
Expand All @@ -48,7 +48,7 @@ const mGetSqliteRouter = createMadonnaFunction({

function getSqliteRouter({ dbPath, config = {} }) {
return getSchema(dbPath)
.then(schema => {
.then((schema) => {
dbSchema.set(schema)
configService.set(config)

Expand Down Expand Up @@ -90,9 +90,9 @@ function getSqliteRouter({ dbPath, config = {} }) {
//-------------//

function getBuildRoutes(router, connections) {
return aStructType => {
return (aStructType) => {
forEachWithKey((columns, name) => {
fp.each(aTableMethod => {
fp.each((aTableMethod) => {
columns = fp.keyBy('name', columns)
routeBuilders[aTableMethod](name, columns, connections, router)
}, aStructType.methods)
Expand All @@ -102,7 +102,7 @@ function getBuildRoutes(router, connections) {

function bGetConnection(dbPath, mode) {
return new bPromise((resolve, reject) => {
const db = new sqlite3.Database(dbPath, mode, err => {
const db = new sqlite3.Database(dbPath, mode, (err) => {
return err ? reject(err) : resolve(db)
})
})
Expand Down
11 changes: 4 additions & 7 deletions lib/api/helpers/get-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ let db // set in `bGetDb`. Needs to have file-wide scope
function getSchema(dbPath) {
return bGetDb(dbPath)
.then(() => db.allAsync(queries.allTablesAndViews))
.then(rows => {
.then((rows) => {
const tableAndViewNames = fp.flow(
fp.partition(['type', 'table']),
reduceWithKey((res, aPartition, index) => {
Expand All @@ -54,10 +54,7 @@ function getSchema(dbPath) {
})
.then(({ flat, partitioned }) => {
const tableAndViewToPragma = fp.mapValues(
fp.flow(
fp.sortBy('cid'),
fp.map(modifyColumnProperties)
),
fp.flow(fp.sortBy('cid'), fp.map(modifyColumnProperties)),
flat
)

Expand Down Expand Up @@ -146,15 +143,15 @@ function isUnnecessary(val, key) {

function bGetDb(dbPath) {
return new bPromise((resolve, reject) => {
db = new sqlite3.Database(dbPath, err => (err ? reject(err) : resolve()))
db = new sqlite3.Database(dbPath, (err) => (err ? reject(err) : resolve()))
})
}

function getQueries() {
return {
allTablesAndViews:
"select name, type from sqlite_master where type='table' or type='view';",
getPragmaTable: tbl => `pragma table_info(${tbl})`,
getPragmaTable: (tbl) => `pragma table_info(${tbl})`,
}
}

Expand Down
38 changes: 11 additions & 27 deletions lib/api/helpers/route-builders/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const { isDefined, startsWith } = utils,
// Main //
//------//

const appendMidParsed = str => '\nquery string (mid-parsed): ' + str
const appendMidParsed = (str) => '\nquery string (mid-parsed): ' + str

const attachError = (ctx, err) => {
ctx.status = 400
Expand All @@ -33,7 +33,7 @@ const attachError = (ctx, err) => {
const bRunQuery = (conn, query, params) => {
return new bPromise((resolve, reject) => {
try {
conn.run(query, params, function(err) {
conn.run(query, params, function (err) {
if (err) reject(err)
else resolve(this)
})
Expand All @@ -43,10 +43,10 @@ const bRunQuery = (conn, query, params) => {
})
}

const bStreamFinished = aStream => {
const bStreamFinished = (aStream) => {
return new bPromise((resolve, reject) => {
try {
stream.finished(aStream, err => {
stream.finished(aStream, (err) => {
if (err) reject(err)
else resolve(aStream)
})
Expand All @@ -56,7 +56,7 @@ const bStreamFinished = aStream => {
})
}

const doesNotHaveFlag = flag => fp.negate(hasFlag(flag))
const doesNotHaveFlag = (flag) => fp.negate(hasFlag(flag))

const getParams = fp.flow(
fp.values,
Expand All @@ -65,16 +65,10 @@ const getParams = fp.flow(
fp.map('val')
)

const getPkColumnNames = fp.flow(
fp.pickBy(isPrimaryKey),
fp.map('name')
)
const getPkColumnNames = fp.flow(fp.pickBy(isPrimaryKey), fp.map('name'))

const getQuery = ({ parsed, queryStart, limit, offset, order }) => {
const parsedPairs = fp.flow(
fp.toPairs,
fp.reduce(flattenParsed, [])
)(parsed)
const parsedPairs = fp.flow(fp.toPairs, fp.reduce(flattenParsed, []))(parsed)

let res = queryStart
if (fp.size(parsed)) {
Expand All @@ -93,11 +87,7 @@ const getQuery = ({ parsed, queryStart, limit, offset, order }) => {
return res
}

const hasFlag = flagVal =>
fp.flow(
fp.get('flags'),
fp.includes(flagVal)
)
const hasFlag = (flagVal) => fp.flow(fp.get('flags'), fp.includes(flagVal))

const isAdjacentToSingleQuote = (i, str) => {
const quoteBefore = i !== 0 && str[i - 1] === "'",
Expand Down Expand Up @@ -180,10 +170,7 @@ function parseQueryForPkColumns(str, pkColumnNames, qsErrIds) {
})
}

const pkColumnsMissing = fp.flow(
fp.pickBy(fp.eq(0)),
fp.keys
)(pkColumnCounts)
const pkColumnsMissing = fp.flow(fp.pickBy(fp.eq(0)), fp.keys)(pkColumnCounts)

if (fp.size(pkColumnsMissing)) {
return {
Expand Down Expand Up @@ -225,13 +212,10 @@ function genWhereClause(res, aPair) {
return res + ' AND ' + pairToCondition(aPair)
}
function flattenParsed(res, aPair) {
return res.concat(fp.map(parsedVal => [aPair[0], parsedVal], aPair[1]))
return res.concat(fp.map((parsedVal) => [aPair[0], parsedVal], aPair[1]))
}
function isPrimaryKey(aColumn) {
return fp.flow(
fp.get('flags'),
fp.contains('isPrimaryKey')
)(aColumn)
return fp.flow(fp.get('flags'), fp.contains('isPrimaryKey'))(aColumn)
}

function getInvalidOrderElements(order, columnNames) {
Expand Down
2 changes: 1 addition & 1 deletion lib/api/helpers/route-builders/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const buildDelete = (name, columns, connections, router) => {
ctx.status = changes ? 204 : 404
return next()
})
.catch(err => {
.catch((err) => {
ctx.status = 500
console.error(err)
})
Expand Down
16 changes: 7 additions & 9 deletions lib/api/helpers/route-builders/get.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ const buildGet = (name, columns, connections, router) => {
ctx.status = isPartialResource ? 206 : 200

eachAsync(connections.readOnly, query, params, stringifyStream)
.catch(err => {
.catch((err) => {
console.error(err)
})
.finally(() => {
stringifyStream.end()
})
})
.catch(err => {
.catch((err) => {
ctx.status = 500
console.error(err)
})
Expand Down Expand Up @@ -259,7 +259,7 @@ function eachAsync(conn, query, params, stringifyStream) {
try {
let rowCount = 0

const stmt = conn.prepare(query, params, err => {
const stmt = conn.prepare(query, params, (err) => {
if (err) {
return bPromise.reject(err)
}
Expand All @@ -278,9 +278,7 @@ function eachAsync(conn, query, params, stringifyStream) {
const shouldContinue = stringifyStream.write(row)

if (!shouldContinue) {
console.log('got here')
stringifyStream.once('drain', () => {
console.log('no drain :(')
stmt.get(recursiveGet)
})
} else {
Expand All @@ -292,7 +290,7 @@ function eachAsync(conn, query, params, stringifyStream) {
stmt.get(recursiveGet)
})

const cleanupAndDone = err => {
const cleanupAndDone = (err) => {
stmt.finalize(() => {
if (err) reject(err)
else resolve(rowCount)
Expand Down Expand Up @@ -490,7 +488,7 @@ function handleNoRangeRequest(

const stringifyStream = (ctx.body = jsonStream.stringify())

stringifyStream.on('error', err => {
stringifyStream.on('error', (err) => {
console.error(err)
stringifyStream.end()
})
Expand All @@ -501,14 +499,14 @@ function handleNoRangeRequest(
}

eachAsync(connections.readOnly, query, params, stringifyStream)
.catch(err => {
.catch((err) => {
console.error(err)
})
.finally(() => {
stringifyStream.end()
})
})
.catch(err => {
.catch((err) => {
ctx.status = 500
console.error(err)
})
Expand Down
2 changes: 1 addition & 1 deletion lib/api/helpers/route-builders/handle-head.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const handleHead = (
.then(() => {
return connections.readOnly.getAsync(query, params)
})
.then(res => {
.then((res) => {
ctx.set('content-range', 'rows */' + res.count)
})
}
Expand Down
10 changes: 5 additions & 5 deletions lib/api/helpers/route-builders/handle-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const handleHead = (ctx, next, name, columns, connections) => {
where

return bRunQuery(connections.readWrite, query, params)
.then(res => {
.then((res) => {
if (!res.changes) {
ctx.status = 404
return next()
Expand All @@ -66,13 +66,13 @@ const handleHead = (ctx, next, name, columns, connections) => {

query = `SELECT * FROM ${name} WHERE ` + where

return connections.readOnly.getAsync(query, params).then(row => {
return connections.readOnly.getAsync(query, params).then((row) => {
ctx.body = row
ctx.set('content-location', `${ctx.path}?${ctx.decodedQuerystring}`)
return next()
})
})
.catch(err => {
.catch((err) => {
ctx.status = 500
console.error(err)
})
Expand Down Expand Up @@ -133,7 +133,7 @@ function getSetClause(reqBody) {
' SET ' +
fp.flow(
fp.keys,
fp.map(col => col + ' = ?'),
fp.map((col) => col + ' = ?'),
fp.join(', ')
)(reqBody),
params: fp.values(reqBody),
Expand All @@ -144,7 +144,7 @@ function getWhereClause(query) {
return {
where: fp.flow(
fp.keys,
fp.map(col => col + ' = ?'),
fp.map((col) => col + ' = ?'),
fp.join(' AND ')
)(query),
params: fp.values(query),
Expand Down
Loading