Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

pgrest

Package Overview
Dependencies
Maintainers
2
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pgrest - npm Package Compare versions

Comparing version 0.0.2 to 0.0.3

lib/routes.js

229

bin/cmd.js
#!/usr/bin/env node
var optimist, plv8x, trycatch, argv, conString, ref$, pgsock, slice$ = [].slice, join$ = [].join;
var optimist, plv8x, argv, conString, ref$, pgsock, pgrest, join$ = [].join;
optimist = require('optimist');
plv8x = require('plv8x');
trycatch = require('trycatch');
argv = optimist.argv;

@@ -19,8 +18,10 @@ conString = argv.db || process.env['PLV8XCONN'] || process.env['PLV8XDB'] || process.env.TESTDBNAME || ((ref$ = process.argv) != null ? ref$[2] : void 8);

}
require('../')['new'](conString, {}, function(plx){
var port, ref$, prefix, express, app, cors, gzippo, connectCsv, schemaCond, route;
pgrest = require('..');
pgrest['new'](conString, {}, function(plx){
var ref$, mountDefault, withPrefix, port, prefix, host, express, app, cors, gzippo, connectCsv;
ref$ = pgrest.routes(), mountDefault = ref$.mountDefault, withPrefix = ref$.withPrefix;
if (argv.boot) {
process.exit(0);
}
port = (ref$ = argv.port) != null ? ref$ : 3000, prefix = (ref$ = argv.prefix) != null ? ref$ : "/collections";
port = (ref$ = argv.port) != null ? ref$ : 3000, prefix = (ref$ = argv.prefix) != null ? ref$ : "/collections", host = (ref$ = argv.host) != null ? ref$ : "127.0.0.1";
express = (function(){

@@ -43,217 +44,9 @@ try {

}));
schemaCond = argv.schema ? "IN ('" + argv.schema + "')" : "NOT IN ( 'information_schema', 'pg_catalog', 'plv8x')";
route = function(path, fn){
return app.all((function(){
switch (path[0]) {
case void 8:
return prefix;
case '/':
return '';
default:
return prefix + "/";
}
}()) + "" + path, cors(), function(req, resp){
var done;
if (req.method === 'OPTION') {
return resp.send(200);
}
resp.setHeader('Content-Type', 'application/json; charset=UTF-8');
done = function(it){
switch (typeof it) {
case 'number':
return resp.send(it(it));
case 'object':
return resp.send(200, JSON.stringify(it));
case 'string':
return resp.send(it + "");
}
};
return trycatch(function(){
return done(fn.call(req, function(it){
return done(it);
}));
}, function(it){
if (it instanceof Error) {
it = it.message;
}
switch (typeof it) {
case 'number':
return resp.send(it, {
error: it
});
case 'object':
return resp.send(500, it);
case 'string':
if (/^\d\d\d$/.exec(it)) {
return resp.send(it, {
error: it
});
} else {
return resp.send(500, {
error: it + ""
});
}
break;
default:
return resp.send(500, {
error: it + ""
});
}
});
});
};
return plx.query("SELECT t.table_schema scm, t.table_name tbl FROM INFORMATION_SCHEMA.TABLES t WHERE t.table_schema " + schemaCond + ";", function(rows){
var seen, defaultSchema, cols, res$, i$, len$, ref$, scm, tbl, schema;
seen = {};
defaultSchema = null;
res$ = [];
for (i$ = 0, len$ = rows.length; i$ < len$; ++i$) {
ref$ = rows[i$], scm = ref$.scm, tbl = ref$.tbl;
schema || (schema = scm);
if (seen[tbl]) {
res$.push(console.log(scm + "." + tbl + " not loaded, " + tbl + " already in use"));
} else {
seen[tbl] = true;
res$.push(mountModel(scm, tbl));
}
}
cols = res$;
defaultSchema == null && (defaultSchema = 'public');
route("", function(){
return cols;
});
route(":name", function(done){
var ref$, name, $, param, cols, TypeMap, insertCols, entries, i$, len$, row, j$, len1$, idx, key, col, typ;
if ((ref$ = this.method) == 'GET' || ref$ == 'DELETE') {
throw 404;
}
if ((ref$ = this.method) != 'POST' && ref$ != 'PUT') {
throw 405;
}
name = this.params.name;
$ = Array.isArray(this.body)
? this.body
: [this.body];
param = {
$: $,
collection: defaultSchema + "." + name
};
cols = {};
TypeMap = {
boolean: 'boolean',
number: 'numeric',
string: 'text',
object: 'plv8x.json'
};
if (Array.isArray($[0])) {
insertCols = $[0], entries = slice$.call($, 1);
for (i$ = 0, len$ = entries.length; i$ < len$; ++i$) {
row = entries[i$];
for (j$ = 0, len1$ = insertCols.length; j$ < len1$; ++j$) {
idx = j$;
key = insertCols[j$];
if (row[idx] != null) {
cols[key] || (cols[key] = TypeMap[typeof row[idx]] || 'plv8x.json');
}
}
}
} else {
for (i$ = 0, len$ = $.length; i$ < len$; ++i$) {
row = $[i$];
for (j$ = 0, len1$ = (ref$ = Object.keys(row)).length; j$ < len1$; ++j$) {
key = ref$[j$];
if (row[key] != null) {
cols[key] || (cols[key] = TypeMap[typeof row[key]] || 'plv8x.json');
}
}
}
}
plx.query("CREATE TABLE \"" + name + "\" (" + (function(){
var ref$, results$ = [];
for (col in ref$ = cols) {
typ = ref$[col];
results$.push(col + " " + typ);
}
return results$;
}()).join(",\n") + ")", function(){
mountModel(schema, name);
return plx.insert(param, done, function(it){
throw it + "";
});
});
});
route('/runCommand', function(){
throw "Not implemented yet";
});
app.listen(port);
return mountDefault(plx, argv.schema, withPrefix(prefix, function(path, r){
return app.all(path, cors(), r);
}), function(cols){
app.listen(port, host);
console.log("Available collections:\n" + join$.call(cols, ' '));
console.log("Serving `" + conString + "` on http://localhost:" + port + prefix);
function mountModel(schema, name){
route(name + "", function(it){
var param, ref$, ref1$, method;
param = (ref$ = {
l: (ref1$ = this.query).l,
sk: ref1$.sk,
c: ref1$.c,
s: ref1$.s,
q: ref1$.q,
fo: ref1$.fo,
u: ref1$.u,
delay: ref1$.delay
}, ref$.collection = schema + "." + name, ref$);
method = (function(){
switch (this.method) {
case 'GET':
return 'select';
case 'POST':
return 'insert';
case 'PUT':
if (param.u) {
return 'upsert';
} else {
return 'replace';
}
break;
case 'DELETE':
return 'remove';
default:
throw 405;
}
}.call(this));
param.$ = this.body;
plx[method].call(plx, param, it, function(it){
throw it + "";
});
});
route(name + "/:_id", function(it){
var param, method;
param = {
l: 1,
fo: true,
collection: schema + "." + name,
q: {
_id: this.params._id
}
};
method = (function(){
switch (this.method) {
case 'GET':
return 'select';
case 'PUT':
return 'upsert';
case 'DELETE':
return 'remove';
default:
throw 405;
}
}.call(this));
param.$ = this.body;
plx[method].call(plx, param, it, function(it){
throw it + "";
});
});
return name;
}
return mountModel;
return console.log("Serving `" + conString + "` on http://" + host + ":" + port + prefix);
});
});

@@ -1,2 +0,2 @@

var plv8x, q, qq, walk, compile, cond, test, evaluate, orderBy, SQL_PrimaryFieldInfo, join$ = [].join, out$ = typeof exports != 'undefined' && exports || this, slice$ = [].slice;
var plv8x, q, qq, walk, compile, cond, test, evaluate, orderBy, routes, SQL_PrimaryFieldInfo, SQL_ColumnsInfo, join$ = [].join, out$ = typeof exports != 'undefined' && exports || this, slice$ = [].slice;
plv8x = require('plv8x');

@@ -17,19 +17,25 @@ exports['new'] = function(conString, config, cb){

return plx.importBundle('pgrest', require.resolve('../package.json'), function(){
return plx.ap(function(){
return plv8x.require('pgrest').boot;
}, [config], function(){
return plx.conn.query(plv8x._mk_func('pgrest_boot', {
config: 'plv8x.json'
}, 'boolean', plv8x.plv8xLift("pgrest", "boot"), {
boot: true
}), function(err){
if (err) {
throw err;
}
return plx.conn.query(plv8x._mk_func('pgrest_boot', {
config: 'plv8x.json'
}, 'boolean', plv8x.plv8xLift("pgrest", "boot"), {
boot: true
}), function(err){
if (err) {
throw err;
}
plx.boot = function(cb){
return plx.ap(function(){
return plv8x.require('pgrest').boot;
}, [config], cb);
};
plx.conn.on('error', function(it){
return console.log('pgerror', it);
});
return plx.boot(function(){
['select', 'upsert', 'insert', 'replace', 'remove'].forEach(function(method){
plx[method] = function(param, cb, onError){
return this.conn.query("select pgrest_" + method + "($1) as ret", [JSON.stringify(param)], function(err, arg$){
var ret;
return this.conn.query("select pgrest_" + method + "($1) as ret", [param], function(err, arg$){
var rows, ret;
if (arg$ != null) {
ret = arg$.rows[0].ret;
rows = arg$.rows;
}

@@ -39,2 +45,3 @@ if (err) {

}
ret = rows[0].ret;
return typeof cb === 'function' ? cb(ret) : void 8;

@@ -64,6 +71,9 @@ });

qq = function(it){
if (it === '*') {
return it;
}
return it.replace(/\.(\d+)/g, function(){
return "[" + (parseInt(RegExp.$1) + 1) + "]";
}).replace(/^(\w+)/, function(){
return RegExp.$1.replace(/"/g, '""') + "";
}).replace(/^([^.]*)/, function(){
return "\"" + RegExp.$1.replace(/"/g, '""') + "\"";
});

@@ -98,3 +108,3 @@ };

}()) + "\n) AS _)";
}.call(this, qq($from + "s", modelTable = qq(model + "s"))));
}.call(this, qq($from + "", modelTable = qq(model + ""))));
case $ == null:

@@ -227,5 +237,8 @@ return cond(model, $);

};
out$.routes = routes = function(){
return require('./routes');
};
out$.select = select;
function select(param){
var i$, ref$, len$, p, collection, l, sk, q, c, s, fo, idColumn, cond, query, count;
var i$, ref$, len$, p, collection, l, sk, q, c, s, f, fo, meta, ref1$, idColumn, cond, that, columns, inclusive, _, v, query, count, maybe_;
for (i$ = 0, len$ = (ref$ = ['l', 'sk', 'c']).length; i$ < len$; ++i$) {

@@ -237,3 +250,3 @@ p = ref$[i$];

}
for (i$ = 0, len$ = (ref$ = ['q', 's']).length; i$ < len$; ++i$) {
for (i$ = 0, len$ = (ref$ = ['q', 's', 'f']).length; i$ < len$; ++i$) {
p = ref$[i$];

@@ -244,4 +257,8 @@ if (typeof param[p] === 'string') {

}
collection = param.collection, l = (ref$ = param.l) != null ? ref$ : 30, sk = (ref$ = param.sk) != null ? ref$ : 0, q = param.q, c = param.c, s = param.s, fo = param.fo;
idColumn = pgrest.PrimaryFieldOf[collection];
collection = param.collection, l = (ref$ = param.l) != null ? ref$ : 30, sk = (ref$ = param.sk) != null ? ref$ : 0, q = param.q, c = param.c, s = param.s, f = param.f, fo = param.fo;
meta = (ref$ = pgrest.config) != null ? (ref1$ = ref$.meta) != null ? ref1$[collection] : void 8 : void 8;
fo == null && (fo = meta != null ? meta.fo : void 8);
f == null && (f = meta != null ? meta.f : void 8);
s == null && (s = meta != null ? meta.s : void 8);
idColumn = pgrest.PrimaryFieldOf[(ref$ = meta != null ? meta.as : void 8) != null ? ref$ : collection];
if ((q != null && q._id) && idColumn) {

@@ -253,3 +270,30 @@ q[idColumn] = q._id, delete q._id;

}
query = "SELECT *" + (idColumn ? ", " + idColumn + " AS _id" : "") + " FROM " + qq(collection);
if (that = pgrest.ColumnsOf[collection]) {
columns = [].concat(that);
if (f) {
inclusive = in$(1, (function(){
var ref$, results$ = [];
for (_ in ref$ = f) {
v = ref$[_];
results$.push(+v);
}
return results$;
}()));
if (inclusive) {
columns = columns.filter(function(it){
return f[it];
});
} else {
columns = columns.filter(function(it){
return f[it] == null || f[it];
});
}
}
} else {
columns = ['*'];
}
if (idColumn) {
columns.push(idColumn);
}
query = "SELECT " + columns.map(qq).join(',') + " FROM " + qq(collection);
if (cond != null) {

@@ -267,4 +311,10 @@ query += " WHERE " + cond;

}
maybe_ = function(it){
while ((it != null ? it._ : void 8) != null) {
it = it._;
}
return it;
};
if (fo) {
return (ref$ = plv8.execute(query + " limit $1 offset $2", [l, sk])) != null ? ref$[0] : void 8;
return maybe_((ref$ = plv8.execute(query + " limit $1 offset $2", [l, sk])) != null ? ref$[0] : void 8);
}

@@ -277,3 +327,3 @@ return {

},
entries: plv8.execute(query + " limit $1 offset $2", [l, sk]),
entries: plv8.execute(query + " limit $1 offset $2", [l, sk]).map(maybe_),
query: cond

@@ -306,4 +356,21 @@ };

}
function refreshMeta(collection){
var ref$, schema, table, column_name, data_type;
pgrest.Meta == null && (pgrest.Meta = {});
ref$ = collection.split('.'), schema = ref$[0], table = ref$[1];
if (!table) {
ref$ = ['public', schema], schema = ref$[0], table = ref$[1];
}
return pgrest.Meta[collection] = (function(){
var i$, ref$, len$, ref1$, results$ = {};
for (i$ = 0, len$ = (ref$ = plv8.execute("select column_name, data_type from information_schema.columns where table_schema = $1 and table_name = $2", [schema, table])).length; i$ < len$; ++i$) {
ref1$ = ref$[i$], column_name = ref1$.column_name, data_type = ref1$.data_type;
results$[column_name] = data_type;
}
return results$;
}());
}
function _insert_statement(collection, insertCols, insertVals){
var values, res$, i$, len$, i, _, v;
var meta, values, res$, i$, len$, i, _, todrop, v, ref$;
meta = pgrest.Meta[collection];
res$ = [];

@@ -316,6 +383,15 @@ for (i$ = 0, len$ = insertCols.length; i$ < len$; ++i$) {

values = res$;
todrop = [];
res$ = [];
for (i$ = 0, len$ = insertVals.length; i$ < len$; ++i$) {
i = i$;
v = insertVals[i$];
if (v != null && typeof v === 'object') {
if (meta[insertCols[i]] == null) {
console.warn(insertCols[i] + " not found, skipping");
todrop.push(i);
continue;
}
if (meta[insertCols[i]] === 'ARRAY') {
res$.push(v);
} else if (v != null && typeof v === 'object') {
res$.push(JSON.stringify(v));

@@ -327,2 +403,7 @@ } else {

insertVals = res$;
for (i$ = 0, len$ = (ref$ = todrop.reverse()).length; i$ < len$; ++i$) {
i = ref$[i$];
insertCols.splice(i, 1);
values.pop();
}
return ["INSERT INTO " + qq(collection) + "(" + insertCols.map(qq).join(',') + ") VALUES (" + values.join(',') + ")", insertVals];

@@ -334,2 +415,3 @@ }

collection = param.collection, $ = param.$;
refreshMeta(collection);
return Array.isArray($) && Array.isArray($[0])

@@ -393,5 +475,4 @@ ? (insertCols = $[0], entries = slice$.call($, 1), (function(){

: {}, q = param.q, delay = param.delay;
$set = (ref$ = $.$set) != null
? ref$
: {};
$set = (ref$ = $.$set) != null ? ref$ : $;
refreshMeta(collection);
if (q) {

@@ -469,3 +550,3 @@ cond = compile(collection, q);

function boot(config){
var serial, deferred, PrimaryFieldOf, i$, ref$, len$, ref1$, key, val, constraint;
var serial, deferred, PrimaryFieldOf, ColumnsOf, i$, ref$, len$, ref1$, key, val, constraint, name, columns;
serial = 0;

@@ -476,3 +557,9 @@ deferred = [];

log: function(){
return plv8.elog.apply(plv8, [INFO].concat(slice$.call(arguments)));
},
warn: function(){
return plv8.elog.apply(plv8, [WARNING].concat(slice$.call(arguments)));
},
error: function(){
return plv8.elog.apply(plv8, [ERROR].concat(slice$.call(arguments)));
}

@@ -501,2 +588,3 @@ };

PrimaryFieldOf = {};
ColumnsOf = {};
for (i$ = 0, len$ = (ref$ = plv8.execute(SQL_PrimaryFieldInfo)).length; i$ < len$; ++i$) {

@@ -508,3 +596,8 @@ ref1$ = ref$[i$], key = ref1$.key, val = ref1$.val, constraint = ref1$.constraint;

}
for (i$ = 0, len$ = (ref$ = plv8.execute(SQL_ColumnsInfo)).length; i$ < len$; ++i$) {
ref1$ = ref$[i$], name = ref1$.name, columns = ref1$.columns;
ColumnsOf[name] = columns;
}
pgrest.PrimaryFieldOf = PrimaryFieldOf;
pgrest.ColumnsOf = ColumnsOf;
pgrest.config = config;

@@ -514,2 +607,3 @@ return true;

SQL_PrimaryFieldInfo = "SELECT t.table_schema || '.' || t.table_name AS key,\n kcu.constraint_name AS constraint,\n array_agg('' || kcu.column_name) AS val\nFROM INFORMATION_SCHEMA.TABLES t\n LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc\n ON tc.table_catalog = t.table_catalog\n AND tc.table_schema = t.table_schema\n AND tc.table_name = t.table_name\n AND tc.constraint_type = 'PRIMARY KEY'\n LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu\n ON kcu.table_catalog = tc.table_catalog\n AND kcu.table_schema = tc.table_schema\n AND kcu.table_name = tc.table_name\n AND kcu.constraint_name = tc.constraint_name\nWHERE t.table_schema NOT IN ('pg_catalog', 'information_schema', 'plv8x')\n AND kcu.column_name IS NOT NULL\nGROUP BY t.table_schema || '.' || t.table_name, kcu.constraint_name";
SQL_ColumnsInfo = "SELECT table_schema || '.' || table_name as name, array_agg('' || column_name) as columns\nFROM information_schema.columns WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'plv8x') group by name;";
function curry$(f, bound){

@@ -527,2 +621,7 @@ var context,

return _curry();
}
function in$(x, arr){
var i = -1, l = arr.length >>> 0;
while (++i < l) if (x === arr[i] && i in arr) return true;
return false;
}

@@ -10,3 +10,3 @@ {

"description": "enable REST in postgres",
"version": "0.0.2",
"version": "0.0.3",
"main": "lib/index.js",

@@ -22,3 +22,4 @@ "bin": {

"test": "env PATH=\"./node_modules/.bin:$PATH\" mocha",
"prepublish": "env PATH=\"./node_modules/.bin:$PATH\" lsc -cj package.ls &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc bin &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc -o lib src"
"prepublish": "env PATH=\"./node_modules/.bin:$PATH\" lsc -cj package.ls &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc bin &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc -o lib src",
"postinstall": "env PATH=\"./node_modules/.bin:$PATH\" lsc -cj package.ls &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc bin &&\nenv PATH=\"./node_modules/.bin:$PATH\" lsc -bc -o lib src"
},

@@ -30,4 +31,4 @@ "engines": {

"optimist": "0.3.x",
"trycatch": "*",
"plv8x": "0.4.x",
"trycatch": "0.2.x",
"plv8x": "0.5.x",
"express": "3.1.x",

@@ -40,2 +41,3 @@ "cors": "0.0.x",

"mocha": "*",
"supertest": "0.7.x",
"chai": "*",

@@ -42,0 +44,0 @@ "LiveScript": "1.1.1"

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc