Skip to content

Commit

Permalink
Restore object structure after select with join
Browse files Browse the repository at this point in the history
  • Loading branch information
nechaido committed Nov 29, 2018
1 parent 8199b8b commit 1e5b1d1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
10 changes: 8 additions & 2 deletions lib/pg.cursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { extractDecorator } = require('metaschema');
const transformations = require('./transformations');
const { SelectBuilder } = require('./sqlgen');
const { Cursor } = require('./cursor');
const { expand } = require('./pg.utils');

const jsqlToSQLConverters = {
select: (op, query) => {
Expand Down Expand Up @@ -57,11 +58,13 @@ class PostgresCursor extends Cursor {
.categories.get(this.category)
.definition;

let needsExpanding = false;
for (const key in schema) {
const field = schema[key];
if (extractDecorator(field) === 'Include') {
const cat = field.category;
pgquery.innerJoin(cat, `${this.category}.Id`, `${cat}.Id`);
needsExpanding = true;
}
}

Expand All @@ -71,8 +74,11 @@ class PostgresCursor extends Cursor {
return;
}
this.jsql = this.jsql.slice(i);
if (this.jsql.length === 0) callback(null, res.rows, this);
else this.continue(res.rows, callback);
const rows = needsExpanding ?
res.rows.map(row => expand(row, schema)) : res.rows;

if (this.jsql.length === 0) callback(null, rows, this);
else this.continue(rows, callback);
});
}
}
Expand Down
19 changes: 19 additions & 0 deletions lib/pg.utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const transformations = require('./transformations');
const { extractDecorator } = require('metaschema');

const escapeString = value => {
let backslash = false;
Expand Down Expand Up @@ -136,6 +137,23 @@ const buildWhere = query => {
}).join(' AND '), params];
};

const expand = (object, schema) => {
const result = {};
if (object.Id) {
result.Id = object.Id;
}
for (const prop in schema) {
const field = schema[prop];
const value = object[prop];
if (value !== undefined) {
result[prop] = value;
} else if (extractDecorator(field) === 'Include') {
result[prop] = expand(object, field.definition);
}
}
return result;
};

module.exports = {
escapeString,
escapeValue,
Expand All @@ -147,4 +165,5 @@ module.exports = {
generateQueryParams,
buildWhere,
classMapping,
expand,
};
2 changes: 1 addition & 1 deletion test/pg.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,6 @@ prepareDB(err => {
}
);
});
}, { todo: true });
});
});
});

0 comments on commit 1e5b1d1

Please sign in to comment.