Skip to content

Commit

Permalink
feat(query): implements basic querying
Browse files Browse the repository at this point in the history
  • Loading branch information
mastilver committed Dec 13, 2016
1 parent 7c6f20f commit 1cc6659
Showing 1 changed file with 73 additions and 1 deletion.
74 changes: 73 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,82 @@ module.exports = function (options) {
});
},

query(/* queryOptions */) {
query(queryOptions) {
queryOptions = queryOptions || {};

const sql = buildQuery(collectionName, queryOptions);

return db.query(sql.query, {
params: sql.params
});
}
};
}
};
};

function buildQuery(collectionName, queryOptions) {
const where = queryOptions.where || {};
const limit = queryOptions.limit;
const offset = queryOptions.offset || 0;
const orderBy = queryOptions.orderBy || [];

const queryParams = [];
let queryString = `
SELECT * from ${collectionName}
`;

const whereString = Object.keys(where).map(prop => {
const operator = Object.keys(where[prop])[0];

switch (operator) {
case '$eq': {
const paramId = addParams(where[prop].$eq);
return `
${prop} = :${paramId}
`;
}
default:
throw new Error(`Operator: ${operator} not handled`);
}
})
.join(' AND ');

if (whereString != '') {
queryString += ` WHERE ${whereString}`;
}

orderBy.forEach(order => {
const asc = order[1] == null || order[1] === true;

queryString += `
ORDER BY ${order[0]} ${asc ? 'ASC' : 'DESC'}
`;
});

if (limit != null) {
queryString += `
LIMIT ${limit}
`;

if (offset !== 0) {
queryString += `
OFFSET ${offset}
`;
}
}

return {
query: `${queryString};`,
params: queryParams.reduce((obj, value, key) => {
return Object.assign({
[`p${key}`]: value
}, obj);
}, {})
};

function addParams(param) {
queryParams.push(param);
return `p${queryParams.length - 1}`;
}
}

0 comments on commit 1cc6659

Please sign in to comment.