Skip to content

Commit

Permalink
no code generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Lars-Erik Roald committed Jul 11, 2023
1 parent 4e25b3f commit 01e307d
Show file tree
Hide file tree
Showing 35 changed files with 2,352 additions and 1,365 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"title": "rdb",
"description": "Object Relational Mapper",
"types": "./typings/index.d.ts",
"types": "./src/index.d.ts",
"keywords": [
"orm",
"sql",
Expand Down
Empty file added pg
Empty file.
Empty file added sap
Empty file.
Empty file added sqlite
Empty file.
56 changes: 56 additions & 0 deletions src/client/clientMap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
function map(fn) {
const handler = {
get(target, prop) {
if (prop === 'map') {
return (...args) => {
console.log(`Called method "${prop}" with arguments:`, args);
return new Proxy(onFinal, handler);
};
} else if (typeof target[prop] !== 'undefined') {
return target[prop];
} else {
return (...args) => {
console.log(`Called method "${prop}" with arguments:`, args);
return new Proxy({}, handler);
};
}
},
apply(target, _thisArg, argumentsList) {
if (target === onFinal) {
return target(...argumentsList);
} else {
console.log(`Called function "${target.name}" with arguments:`, argumentsList);
return new Proxy({}, handler);
}
},
set(target, prop, value) {
console.log(`Set property "${prop}" to value:`, value);
target[prop] = value;
return true;
},
};

const dbMap = {
http: (url) => url,
pg: throwDb,
postgres: throwDb,
mssql: throwDb,
mssqlNative: throwDb,
mysql: throwDb,
sap: throwDb,
sqlite: throwDb,
};

function throwDb() {
throw new Error('Cannot create pool for database outside node');
}

function onFinal(arg) {
if (arg.db && typeof arg === 'function') {
arg.db = arg.db(dbMap);
}
return fn(arg);
}
}

module.exports = map;
2 changes: 2 additions & 0 deletions src/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const rootMap = new WeakMap();
const fetchingStrategyMap = new WeakMap();
const targetKey = Symbol();
const _axios = require('axios');
const map = require('./clientMap');
const clone = require('rfdc/default');


Expand All @@ -25,6 +26,7 @@ function rdbClient(options = {}) {
}

client.reactive = (cb => _reactive = cb);
client.map = map.bind(null, client);
Object.defineProperty(client, 'metaData', {
get: getMetaData,
enumerable: true,
Expand Down
87 changes: 87 additions & 0 deletions src/client/map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const _newTable = require('../table');

function mapRoot(index, fn) {
return map(index, context, fn);

function context(arg) {
const dbMap = {
pg: createPool.bind(null, index.pg),
postgres: createPool.bind(null, index.pg),
mssql: createPool.bind(null, index.mssql),
mssqlNative: createPool.bind(null, index.mssqlNative),
mysql: createPool.bind(null, index.mysql),
sap: createPool.bind(null, index.sap),
sqlite: createPool.bind(null, index.sqlite),
};

function createPool(provider, ...args) {
const pool = provider.apply(null, args);
const tables = {};
for (let name in context) {
if (context[name] && context[name]._dbName)
tables[name] = context[name];
}
return index({ db: () => pool, tables });
}

if (arg && arg.db && typeof arg.db === 'function') {
return arg.db(dbMap);
}
else
return context;
}
}

function map(index, context, fn) {
let next = fn({ table: newTable, ...context });

for (let name in next) {
if (next[name] && next[name]._dbName) {
context[name] = next[name];
context[name].map = mapTable.bind(null, context[name]);
}
}
context.map = map.bind(null, index, context);
return context;

function newTable() {
let table = _newTable.apply(null, arguments);
table.map = mapTable.bind(null, table);
return table;
}
}

function mapTable(table, fn) {
let next = fn({ column: table.column, primaryColumn: table.primaryColumn, references: table.join, hasMany, hasOne });
for (let name in next) {
if (next[name].as)
next[name] = next[name].as(name);
}

function hasMany(to) {
if (!to)
throw new Error('Missing \'to\' table');
return { by };

function by() {
const join = to.join(table).by.apply(null, arguments);
return table.hasMany(join);
}
}

function hasOne(to) {
if (!to)
throw new Error('Missing \'to\' table');
return { by };

function by() {
const join = to.join(table).by.apply(null, arguments);
return table.hasOne(join);
}
}

return table;

}

module.exports = mapRoot;
46 changes: 37 additions & 9 deletions src/hostExpress/executePath.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
let emptyFilter = require('../emptyFilter');
let negotiateRawSqlFilter = require('../table/column/negotiateRawSqlFilter');
let getMeta = require('./getMeta');
let isSafe = Symbol();
let _ops = {
and: emptyFilter.and,
Expand Down Expand Up @@ -55,7 +56,7 @@ let _allowedOps = {
};

async function executePath({ table, JSONFilter, baseFilter, customFilters = {}, request, response, readonly, disableBulkDeletes, isBrowser, client }) {
let allowedOps = {..._allowedOps, insert: !readonly, insertAndForget: !readonly};
let allowedOps = { ..._allowedOps, insert: !readonly, insertAndForget: !readonly, ...extractRelations(getMeta(table)) };
let ops = { ..._ops, ...getCustomFilterPaths(customFilters), getManyDto, getMany, delete: _delete, cascadeDelete };
let res = await parseFilter(JSONFilter, table) || {};
return res;
Expand Down Expand Up @@ -101,11 +102,11 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},

async function invokeBaseFilter() {
if (typeof baseFilter === 'function') {
const context = {client: client.bindTransaction(), request, response};
const context = { client: client.bindTransaction(), request, response };
const res = await baseFilter.apply(null, [context]);
const JSONFilter = JSON.parse(JSON.stringify(res));
//@ts-ignore
return executePath({ table, JSONFilter, request, response});
return executePath({ table, JSONFilter, request, response });
}
else
return baseFilter;
Expand All @@ -125,13 +126,13 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
}

async function resolveFilter(fn, ...args) {
const context = {client: client.bindTransaction(), request, response};
let res = fn.apply(null, [context, ...args]);
const context = { client: client.bindTransaction(), request, response };
let res = fn.apply(null, [context, ...args]);
if (res.then)
res = await res;
const JSONFilter = JSON.parse(JSON.stringify(res));
//@ts-ignore
return executePath({ table, JSONFilter, request, response});
return executePath({ table, JSONFilter, request, response });
}
}

Expand All @@ -140,13 +141,21 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
let ops = new Set(['all', 'any', 'none']);
let last = path.slice(-1)[0];
if (ops.has(last)) {
for (let i = 0; i < path.length-1; i++) {
for (let i = 0; i < path.length - 1; i++) {
table = table[path[i]];
}
return table._shallow;
}
else
return table;
else {
let lastObj = table;
for (let i = 0; i < path.length; i++) {
if (lastObj)
lastObj = lastObj[path[i]];
}
if (lastObj?._shallow)
return lastObj._shallow;
else return table;
}
}

async function _delete(filter) {
Expand Down Expand Up @@ -276,4 +285,23 @@ function setSafe(o) {
enumerable: false
});
}

function extractRelations(obj) {
let flattened = {};

function helper(relations) {
Object.keys(relations).forEach(key => {

flattened[key] = true;

if (typeof relations[key] === 'object' && Object.keys(relations[key]?.relations)?.length > 0) {
helper(relations[key].relations);
}
});
}

helper(obj.relations);

return flattened;
}
module.exports = executePath;
4 changes: 4 additions & 0 deletions typings/index.d.ts → src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Options } from 'ajv';
import { RequestHandler } from 'express';
import { ConnectionConfig } from 'tedious';
import { AllowedDbMap, DbMapper, MappedDbDef } from './map';

declare function r(config: r.Config): unknown;

Expand All @@ -17,6 +18,9 @@ declare namespace r {
function mysql(connectionString: string, options?: PoolOptions): Pool;
function on(type: 'query', cb: (e: QueryEvent) => void): void;
function off(type: 'query', cb: (e: QueryEvent) => void): void;
function map<V extends AllowedDbMap<V>>(
fn: (mapper: DbMapper<{}>) => V
): MappedDbDef<V>;
function createPatch(original: any[], modified: any[]): JsonPatch;
function createPatch(original: any, modified: any): JsonPatch;

Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var _mssqlNative;
var _sap;
var _mssql;
var flags = require('./flags');
var map = require('./client/map');

var connectViaPool = function(connectionString) {
if (connectionString.indexOf && connectionString.indexOf('mysql') === 0)
Expand All @@ -28,6 +29,7 @@ connectViaPool.off = require('./table/log').off;
connectViaPool.query = require('./query');
connectViaPool.lock = require('./lock');
connectViaPool.schema = require('./pg/schema');
connectViaPool.map = map.bind(null, connectViaPool);

Object.defineProperty(connectViaPool, 'mysql', {
get: function() {
Expand Down
Loading

0 comments on commit 01e307d

Please sign in to comment.