New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nocobase/resourcer

Package Overview
Dependencies
Maintainers
1
Versions
527
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nocobase/resourcer - npm Package Compare versions

Comparing version 0.7.0-alpha.34 to 0.7.0-alpha.56

288

lib/action.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Action = void 0;
const lodash_1 = __importDefault(require("lodash"));
const koa_compose_1 = __importDefault(require("koa-compose"));
const utils_1 = require("./utils");
const middleware_1 = __importDefault(require("./middleware"));
const assign_1 = require("./assign");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.Action = void 0;
function _lodash() {
const data = _interopRequireDefault(require("lodash"));
_lodash = function _lodash() {
return data;
};
return data;
}
function _koaCompose() {
const data = _interopRequireDefault(require("koa-compose"));
_koaCompose = function _koaCompose() {
return data;
};
return data;
}
var _utils = require("./utils");
var _middleware = _interopRequireDefault(require("./middleware"));
var _assign = require("./assign");
const _excluded = ["middleware", "middlewares", "handler"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
class Action {
constructor(options) {
this.context = {};
this.params = {};
this.middlewares = [];
options = (0, utils_1.requireModule)(options);
if (typeof options === 'function') {
options = { handler: options };
}
const { middleware, middlewares = [], handler } = options, params = __rest(options, ["middleware", "middlewares", "handler"]);
this.middlewares = middleware_1.default.toInstanceArray(middleware || middlewares);
this.handler = handler;
this.options = options;
this.mergeParams(params);
constructor(options) {
this.handler = void 0;
this.resource = void 0;
this.name = void 0;
this.options = void 0;
this.context = {};
this.params = {};
this.actionName = void 0;
this.resourceName = void 0;
this.resourceOf = void 0;
this.middlewares = [];
options = (0, _utils.requireModule)(options);
if (typeof options === 'function') {
options = {
handler: options
};
}
clone() {
const options = lodash_1.default.cloneDeep(this.options);
delete options.middleware;
delete options.middlewares;
const action = new Action(options);
action.setName(this.name);
action.setResource(this.resource);
action.middlewares.push(...this.middlewares);
return action;
const _options = options,
middleware = _options.middleware,
_options$middlewares = _options.middlewares,
middlewares = _options$middlewares === void 0 ? [] : _options$middlewares,
handler = _options.handler,
params = _objectWithoutProperties(_options, _excluded);
this.middlewares = _middleware.default.toInstanceArray(middleware || middlewares);
this.handler = handler;
this.options = options;
this.mergeParams(params);
}
clone() {
const options = _lodash().default.cloneDeep(this.options);
delete options.middleware;
delete options.middlewares;
const action = new Action(options);
action.setName(this.name);
action.setResource(this.resource);
action.middlewares.push(...this.middlewares);
return action;
}
setContext(context) {
this.context = context;
}
mergeParams(params, strategies = {}) {
(0, _assign.assign)(this.params, params, _objectSpread({
filter: 'andMerge',
fields: 'intersect',
appends: 'union',
except: 'union',
whitelist: 'intersect',
blacklist: 'intersect',
sort: 'overwrite'
}, strategies));
}
setResource(resource) {
this.resource = resource;
return this;
}
getResource() {
return this.resource;
}
getOptions() {
return this.options;
}
setName(name) {
this.name = name;
return this;
}
getName() {
return this.name;
}
getMiddlewareHandlers() {
return this.middlewares.filter(middleware => middleware.canAccess(this.name)).map(middleware => middleware.getHandler());
}
getHandler() {
const handler = (0, _utils.requireModule)(this.handler || this.resource.resourcer.getRegisteredHandler(this.name));
if (typeof handler !== 'function') {
throw new Error('Handler must be a function!');
}
setContext(context) {
this.context = context;
}
mergeParams(params, strategies = {}) {
(0, assign_1.assign)(this.params, params, Object.assign({ filter: 'andMerge', fields: 'intersect', appends: 'union', except: 'union', whitelist: 'intersect', blacklist: 'intersect', sort: 'overwrite' }, strategies));
}
setResource(resource) {
this.resource = resource;
return this;
}
getResource() {
return this.resource;
}
getOptions() {
return this.options;
}
setName(name) {
this.name = name;
return this;
}
getName() {
return this.name;
}
getMiddlewareHandlers() {
return this.middlewares
.filter((middleware) => middleware.canAccess(this.name))
.map((middleware) => middleware.getHandler());
}
getHandler() {
const handler = (0, utils_1.requireModule)(this.handler || this.resource.resourcer.getRegisteredHandler(this.name));
if (typeof handler !== 'function') {
throw new Error('Handler must be a function!');
}
return handler;
}
getHandlers() {
return [...this.resource.resourcer.getMiddlewares(), ...this.getMiddlewareHandlers(), this.getHandler()].filter(Boolean);
}
execute(context, next) {
return __awaiter(this, void 0, void 0, function* () {
return yield (0, koa_compose_1.default)(this.getHandlers())(context, next);
});
}
static toInstanceMap(actions, resource) {
return new Map(Object.entries(actions).map(([key, options]) => {
let action;
if (options instanceof Action) {
action = options;
}
else {
action = new Action(options);
}
action.setName(key);
action.setResource(resource);
resource && action.middlewares.unshift(...resource.middlewares);
return [key, action];
}));
}
return handler;
}
getHandlers() {
return [...this.resource.resourcer.getMiddlewares(), ...this.getMiddlewareHandlers(), this.getHandler()].filter(Boolean);
}
execute(context, next) {
var _this = this;
return _asyncToGenerator(function* () {
return yield (0, _koaCompose().default)(_this.getHandlers())(context, next);
})();
}
static toInstanceMap(actions, resource) {
return new Map(Object.entries(actions).map(([key, options]) => {
let action;
if (options instanceof Action) {
action = options;
} else {
action = new Action(options);
}
action.setName(key);
action.setResource(resource);
resource && action.middlewares.unshift(...resource.middlewares);
return [key, action];
}));
}
}
exports.Action = Action;
exports.default = Action;
//# sourceMappingURL=action.js.map
var _default = Action;
exports.default = _default;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assign = exports.mergeStrategies = void 0;
const lodash_1 = __importDefault(require("lodash"));
const deepmerge_1 = __importDefault(require("deepmerge"));
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assign = assign;
exports.default = isPlainObject;
exports.mergeStrategies = void 0;
function _lodash() {
const data = _interopRequireDefault(require("lodash"));
_lodash = function _lodash() {
return data;
};
return data;
}
function _deepmerge() {
const data = _interopRequireDefault(require("deepmerge"));
_deepmerge = function _deepmerge() {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
exports.default = isPlainObject;
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols
? Object.getOwnPropertySymbols(target).filter((symbol) => target.propertyIsEnumerable(symbol))
: [];
return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(symbol => target.propertyIsEnumerable(symbol)) : [];
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
exports.mergeStrategies = new Map();
exports.mergeStrategies.set('overwrite', (_, y) => {
const mergeStrategies = new Map();
exports.mergeStrategies = mergeStrategies;
mergeStrategies.set('overwrite', (_, y) => {
return y;
});
mergeStrategies.set('andMerge', (x, y) => {
if (!x && !y) {
return;
}
if (!x) {
return y;
}
if (!y) {
return x;
}
return {
$and: [x, y]
};
});
exports.mergeStrategies.set('andMerge', (x, y) => {
if (!x && !y) {
return;
}
if (!x) {
return y;
}
if (!y) {
return x;
}
return {
$and: [x, y],
};
mergeStrategies.set('orMerge', (x, y) => {
if (!x && !y) {
return;
}
if (!x) {
return y;
}
if (!y) {
return x;
}
return {
$or: [x, y]
};
});
exports.mergeStrategies.set('orMerge', (x, y) => {
if (!x && !y) {
return;
}
if (!x) {
return y;
}
if (!y) {
return x;
}
return {
$or: [x, y],
};
mergeStrategies.set('deepMerge', (x, y) => {
return isPlainObject(x) && isPlainObject(y) ? (0, _deepmerge().default)(x, y, {
arrayMerge: (x, y) => y
}) : y;
});
exports.mergeStrategies.set('deepMerge', (x, y) => {
return isPlainObject(x) && isPlainObject(y)
? (0, deepmerge_1.default)(x, y, {
arrayMerge: (x, y) => y,
})
: y;
mergeStrategies.set('merge', (x, y) => {
return isPlainObject(x) && isPlainObject(y) ? Object.assign(x, y) : y;
});
exports.mergeStrategies.set('merge', (x, y) => {
return isPlainObject(x) && isPlainObject(y) ? Object.assign(x, y) : y;
mergeStrategies.set('union', (x, y) => {
if (typeof x === 'string') {
x = x.split(',');
}
if (typeof y === 'string') {
y = y.split(',');
}
return _lodash().default.uniq((x || []).concat(y || []));
});
exports.mergeStrategies.set('union', (x, y) => {
if (typeof x === 'string') {
x = x.split(',');
}
if (typeof y === 'string') {
y = y.split(',');
}
return lodash_1.default.uniq((x || []).concat(y || []));
mergeStrategies.set('intersect', (x, y) => {
if (typeof x === 'string') {
x = x.split(',');
}
if (typeof y === 'string') {
y = y.split(',');
}
if (!Array.isArray(x) || x.length === 0) {
return y || [];
}
if (!Array.isArray(y) || y.length === 0) {
return x || [];
}
return x.filter(v => y.includes(v));
});
exports.mergeStrategies.set('intersect', (x, y) => {
if (typeof x === 'string') {
x = x.split(',');
function assign(target, source, strategies = {}) {
getKeys(source).forEach(sourceKey => {
const strategy = strategies[sourceKey];
let func = mergeStrategies.get('deepMerge');
if (typeof strategy === 'function') {
func = strategy;
} else if (typeof strategy === 'string' && mergeStrategies.has(strategy)) {
func = mergeStrategies.get(strategy);
}
if (typeof y === 'string') {
y = y.split(',');
}
if (!Array.isArray(x) || x.length === 0) {
return y || [];
}
if (!Array.isArray(y) || y.length === 0) {
return x || [];
}
return x.filter((v) => y.includes(v));
});
function assign(target, source, strategies = {}) {
getKeys(source).forEach((sourceKey) => {
const strategy = strategies[sourceKey];
let func = exports.mergeStrategies.get('deepMerge');
if (typeof strategy === 'function') {
func = strategy;
}
else if (typeof strategy === 'string' && exports.mergeStrategies.has(strategy)) {
func = exports.mergeStrategies.get(strategy);
}
target[sourceKey] = func(target[sourceKey], source[sourceKey]);
});
return target;
}
exports.assign = assign;
//# sourceMappingURL=assign.js.map
target[sourceKey] = func(target[sourceKey], source[sourceKey]);
});
return target;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const resourcer_1 = __importDefault(require("./resourcer"));
__exportStar(require("./utils"), exports);
__exportStar(require("./middleware"), exports);
__exportStar(require("./action"), exports);
__exportStar(require("./resource"), exports);
__exportStar(require("./resourcer"), exports);
exports.default = resourcer_1.default;
//# sourceMappingURL=index.js.map
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {};
exports.default = void 0;
var _resourcer = _interopRequireWildcard(require("./resourcer"));
Object.keys(_resourcer).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _resourcer[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _resourcer[key];
}
});
});
var _utils = require("./utils");
Object.keys(_utils).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _utils[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _utils[key];
}
});
});
var _middleware = require("./middleware");
Object.keys(_middleware).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _middleware[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _middleware[key];
}
});
});
var _action = require("./action");
Object.keys(_action).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _action[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _action[key];
}
});
});
var _resource = require("./resource");
Object.keys(_resource).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _resource[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _resource[key];
}
});
});
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _default = _resourcer.default;
exports.default = _default;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Middleware = void 0;
const utils_1 = require("./utils");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.Middleware = void 0;
var _utils = require("./utils");
class Middleware {
constructor(options) {
options = (0, utils_1.requireModule)(options);
if (typeof options === 'function') {
this.options = { handler: options };
}
else {
this.options = options;
}
constructor(options) {
this.options = void 0;
options = (0, _utils.requireModule)(options);
if (typeof options === 'function') {
this.options = {
handler: options
};
} else {
this.options = options;
}
getHandler() {
const handler = (0, utils_1.requireModule)(this.options.handler);
if (typeof handler !== 'function') {
throw new Error('Handler must be a function!');
}
return handler;
}
getHandler() {
const handler = (0, _utils.requireModule)(this.options.handler);
if (typeof handler !== 'function') {
throw new Error('Handler must be a function!');
}
canAccess(name) {
const { only = [], except = [] } = this.options;
if (only.length > 0) {
return only.includes(name);
}
if (except.length > 0) {
return !except.includes(name);
}
return true;
return handler;
}
canAccess(name) {
const _this$options = this.options,
_this$options$only = _this$options.only,
only = _this$options$only === void 0 ? [] : _this$options$only,
_this$options$except = _this$options.except,
except = _this$options$except === void 0 ? [] : _this$options$except;
if (only.length > 0) {
return only.includes(name);
}
static toInstanceArray(middlewares) {
if (!middlewares) {
return [];
}
if (!Array.isArray(middlewares)) {
middlewares = [middlewares];
}
return middlewares.map((middleware) => {
if (middleware instanceof Middleware) {
return middleware;
}
if (typeof middleware === 'object') {
return new Middleware(middleware);
}
if (typeof middleware === 'function') {
return new Middleware({ handler: middleware });
}
if (except.length > 0) {
return !except.includes(name);
}
return true;
}
static toInstanceArray(middlewares) {
if (!middlewares) {
return [];
}
if (!Array.isArray(middlewares)) {
middlewares = [middlewares];
}
return middlewares.map(middleware => {
if (middleware instanceof Middleware) {
return middleware;
}
if (typeof middleware === 'object') {
return new Middleware(middleware);
}
if (typeof middleware === 'function') {
return new Middleware({
handler: middleware
});
}
}
});
}
}
exports.Middleware = Middleware;
exports.default = Middleware;
//# sourceMappingURL=middleware.js.map
var _default = Middleware;
exports.default = _default;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Resource = void 0;
const lodash_1 = __importDefault(require("lodash"));
const middleware_1 = __importDefault(require("./middleware"));
const action_1 = __importDefault(require("./action"));
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.Resource = void 0;
function _lodash() {
const data = _interopRequireDefault(require("lodash"));
_lodash = function _lodash() {
return data;
};
return data;
}
var _middleware = _interopRequireDefault(require("./middleware"));
var _action = _interopRequireDefault(require("./action"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
class Resource {
constructor(options, resourcer) {
this.actions = new Map();
const { middleware, middlewares, actions = {} } = options;
this.options = options;
this.resourcer = resourcer;
this.middlewares = middleware_1.default.toInstanceArray(middleware || middlewares);
let excludes = [];
for (const [name, handler] of resourcer.getRegisteredHandlers()) {
if (!actions[name]) {
actions[name] = handler;
}
constructor(options, resourcer) {
this.resourcer = void 0;
this.middlewares = void 0;
this.actions = new Map();
this.options = void 0;
this.except = void 0;
const middleware = options.middleware,
middlewares = options.middlewares,
_options$actions = options.actions,
actions = _options$actions === void 0 ? {} : _options$actions;
this.options = options;
this.resourcer = resourcer;
this.middlewares = _middleware.default.toInstanceArray(middleware || middlewares);
let excludes = [];
var _iterator = _createForOfIteratorHelper(resourcer.getRegisteredHandlers()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const _step$value = _slicedToArray(_step.value, 2),
name = _step$value[0],
handler = _step$value[1];
if (!actions[name]) {
actions[name] = handler;
}
const { only = [], except = [] } = options;
if (except.length > 0) {
excludes = except;
}
else if (only.length > 0) {
excludes = Object.keys(actions).filter((name) => !only.includes(name));
}
this.except = excludes;
this.actions = action_1.default.toInstanceMap(lodash_1.default.omit(actions, excludes), this);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
getName() {
return this.options.name;
const _options$only = options.only,
only = _options$only === void 0 ? [] : _options$only,
_options$except = options.except,
except = _options$except === void 0 ? [] : _options$except;
if (except.length > 0) {
excludes = except;
} else if (only.length > 0) {
excludes = Object.keys(actions).filter(name => !only.includes(name));
}
getExcept() {
return this.except;
this.except = excludes;
this.actions = _action.default.toInstanceMap(_lodash().default.omit(actions, excludes), this);
}
getName() {
return this.options.name;
}
getExcept() {
return this.except;
}
getAction(action) {
if (this.except.includes(action)) {
throw new Error(`${action} action is not allowed`);
}
getAction(action) {
if (this.except.includes(action)) {
throw new Error(`${action} action is not allowed`);
}
if (!this.actions.has(action)) {
throw new Error(`${action} action does not exist`);
}
return this.actions.get(action);
if (!this.actions.has(action)) {
throw new Error(`${action} action does not exist`);
}
return this.actions.get(action);
}
}
exports.Resource = Resource;
exports.default = Resource;
//# sourceMappingURL=resource.js.map
var _default = Resource;
exports.default = _default;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.Resourcer = void 0;
function _glob() {
const data = _interopRequireDefault(require("glob"));
_glob = function _glob() {
return data;
};
return data;
}
function _koaCompose() {
const data = _interopRequireDefault(require("koa-compose"));
_koaCompose = function _koaCompose() {
return data;
};
return data;
}
function _lodash() {
const data = _interopRequireDefault(require("lodash"));
_lodash = function _lodash() {
return data;
};
return data;
}
function _pathToRegexp() {
const data = require("path-to-regexp");
_pathToRegexp = function _pathToRegexp() {
return data;
};
return data;
}
var _resource = _interopRequireDefault(require("./resource"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
class Resourcer {
/**
* 全局定义的 action handlers
*/
constructor(options = {}) {
this.resources = new Map();
this.handlers = new Map();
this.actionHandlers = new Map();
this.middlewareHandlers = new Map();
this.middlewares = [];
this.options = void 0;
this.options = options;
}
/**
* 载入指定目录下的 resource 配置(配置的文件驱动)
*
* TODO: 配置的文件驱动现在会全部初始化,大数据时可能存在性能瓶颈,后续可以加入动态加载
*
* @param {object} [options]
* @param {string} [options.directory] 指定配置所在路径
* @param {array} [options.extensions = ['js', 'ts', 'json']] 文件后缀
*/
import(options) {
const _options$extensions = options.extensions,
extensions = _options$extensions === void 0 ? ['js', 'ts', 'json'] : _options$extensions,
directory = options.directory;
const patten = `${directory}/*.{${extensions.join(',')}}`;
const files = _glob().default.sync(patten, {
ignore: ['**/*.d.ts']
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Resourcer = void 0;
const glob_1 = __importDefault(require("glob"));
const koa_compose_1 = __importDefault(require("koa-compose"));
const lodash_1 = __importDefault(require("lodash"));
const path_to_regexp_1 = require("path-to-regexp");
const resource_1 = __importDefault(require("./resource"));
const utils_1 = require("./utils");
class Resourcer {
constructor(options = {}) {
this.resources = new Map();
/**
* 全局定义的 action handlers
*/
this.handlers = new Map();
this.actionHandlers = new Map();
this.middlewareHandlers = new Map();
this.middlewares = [];
this.options = options;
const resources = new Map();
files.forEach(file => {
const options = (0, _utils.requireModule)(file);
const table = this.define(typeof options === 'function' ? options(this) : options);
resources.set(table.getName(), table);
});
return resources;
}
/**
* resource 配置
*
* @param name
* @param options
*/
define(options) {
const name = options.name;
const resource = new _resource.default(options, this);
this.resources.set(name, resource);
return resource;
}
isDefined(name) {
return this.resources.has(name);
}
registerAction(name, handler) {
this.registerActionHandler(name, handler);
}
registerActions(handlers) {
this.registerActionHandlers(handlers);
}
/**
* 注册全局的 action handlers
*
* @param handlers
*/
registerActionHandlers(handlers) {
for (var _i = 0, _Object$entries = Object.entries(handlers); _i < _Object$entries.length; _i++) {
const _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
name = _Object$entries$_i[0],
handler = _Object$entries$_i[1];
this.registerActionHandler(name, handler);
}
/**
* 载入指定目录下的 resource 配置(配置的文件驱动)
*
* TODO: 配置的文件驱动现在会全部初始化,大数据时可能存在性能瓶颈,后续可以加入动态加载
*
* @param {object} [options]
* @param {string} [options.directory] 指定配置所在路径
* @param {array} [options.extensions = ['js', 'ts', 'json']] 文件后缀
*/
import(options) {
const { extensions = ['js', 'ts', 'json'], directory } = options;
const patten = `${directory}/*.{${extensions.join(',')}}`;
const files = glob_1.default.sync(patten, {
ignore: ['**/*.d.ts'],
});
const resources = new Map();
files.forEach((file) => {
const options = (0, utils_1.requireModule)(file);
const table = this.define(typeof options === 'function' ? options(this) : options);
resources.set(table.getName(), table);
});
return resources;
}
registerActionHandler(name, handler) {
this.actionHandlers.set(name, handler);
}
getRegisteredHandler(name) {
return this.actionHandlers.get(name);
}
getRegisteredHandlers() {
return this.actionHandlers;
}
getResource(name) {
if (!this.resources.has(name)) {
throw new Error(`${name} resource does not exist`);
}
/**
* resource 配置
*
* @param name
* @param options
*/
define(options) {
const { name } = options;
const resource = new resource_1.default(options, this);
this.resources.set(name, resource);
return resource;
return this.resources.get(name);
}
getAction(name, action) {
// 支持注册局部 action
if (this.actionHandlers.has(`${name}:${action}`)) {
return this.getResource(name).getAction(`${name}:${action}`);
}
isDefined(name) {
return this.resources.has(name);
return this.getResource(name).getAction(action);
}
getMiddlewares() {
return this.middlewares;
}
use(middlewares) {
if (typeof middlewares === 'function') {
this.middlewares.push(middlewares);
} else if (Array.isArray(middlewares)) {
this.middlewares.push(...middlewares);
}
registerAction(name, handler) {
this.registerActionHandler(name, handler);
}
registerActions(handlers) {
this.registerActionHandlers(handlers);
}
/**
* 注册全局的 action handlers
*
* @param handlers
*/
registerActionHandlers(handlers) {
for (const [name, handler] of Object.entries(handlers)) {
this.registerActionHandler(name, handler);
}
restApiMiddleware(options = {}) {
var _this = this;
const prefix = options.prefix,
accessors = options.accessors;
const restApiMiddleware = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(function* (ctx, next) {
ctx.resourcer = _this;
let params = (0, _utils.parseRequest)({
path: ctx.request.path,
method: ctx.request.method
}, {
prefix: _this.options.prefix || prefix,
accessors: _this.options.accessors || accessors
});
if (!params) {
return next();
}
}
registerActionHandler(name, handler) {
this.actionHandlers.set(name, handler);
}
getRegisteredHandler(name) {
return this.actionHandlers.get(name);
}
getRegisteredHandlers() {
return this.actionHandlers;
}
getResource(name) {
if (!this.resources.has(name)) {
throw new Error(`${name} resource does not exist`);
}
return this.resources.get(name);
}
getAction(name, action) {
// 支持注册局部 action
if (this.actionHandlers.has(`${name}:${action}`)) {
return this.getResource(name).getAction(`${name}:${action}`);
}
return this.getResource(name).getAction(action);
}
getMiddlewares() {
return this.middlewares;
}
use(middlewares) {
if (typeof middlewares === 'function') {
this.middlewares.push(middlewares);
}
else if (Array.isArray(middlewares)) {
this.middlewares.push(...middlewares);
}
}
restApiMiddleware(options = {}) {
const { prefix, accessors } = options;
const restApiMiddleware = (ctx, next) => __awaiter(this, void 0, void 0, function* () {
ctx.resourcer = this;
let params = (0, utils_1.parseRequest)({
path: ctx.request.path,
method: ctx.request.method,
try {
const resource = _this.getResource((0, _utils.getNameByParams)(params)); // 为关系资源时,暂时需要再执行一遍 parseRequest
if (resource.options.type && resource.options.type !== 'single') {
params = (0, _utils.parseRequest)({
path: ctx.request.path,
method: ctx.request.method,
type: resource.options.type
}, {
prefix: this.options.prefix || prefix,
accessors: this.options.accessors || accessors,
prefix: _this.options.prefix || prefix,
accessors: _this.options.accessors || accessors
});
if (!params) {
return next();
return next();
}
try {
const resource = this.getResource((0, utils_1.getNameByParams)(params));
// 为关系资源时,暂时需要再执行一遍 parseRequest
if (resource.options.type && resource.options.type !== 'single') {
params = (0, utils_1.parseRequest)({
path: ctx.request.path,
method: ctx.request.method,
type: resource.options.type,
}, {
prefix: this.options.prefix || prefix,
accessors: this.options.accessors || accessors,
});
if (!params) {
return next();
}
}
// action 需要 clone 之后再赋给 ctx
ctx.action = this.getAction((0, utils_1.getNameByParams)(params), params.actionName).clone();
ctx.action.setContext(ctx);
ctx.action.actionName = params.actionName;
ctx.action.resourceOf = params.associatedIndex;
ctx.action.resourceName = params.associatedName
? `${params.associatedName}.${params.resourceName}`
: params.resourceName;
ctx.action.params.filterByTk = params.resourceIndex;
const query = (0, utils_1.parseQuery)(ctx.request.querystring);
if ((0, path_to_regexp_1.pathToRegexp)('/resourcer/{:associatedName.}?:resourceName{\\::actionName}').test(ctx.request.path)) {
ctx.action.mergeParams(Object.assign(Object.assign(Object.assign({}, query), params), ctx.request.body));
}
else {
ctx.action.mergeParams(Object.assign(Object.assign(Object.assign({}, query), params), (lodash_1.default.isEmpty(ctx.request.body) ? {} : { values: ctx.request.body })));
}
return (0, koa_compose_1.default)(ctx.action.getHandlers())(ctx, next);
}
catch (error) {
return next();
}
});
return restApiMiddleware;
}
middleware(options = {}) {
return this.restApiMiddleware(options);
}
/**
* 实验性 API
*
* @param options
* @param context
* @param next
*/
execute(options, context = {}, next) {
return __awaiter(this, void 0, void 0, function* () {
const { resource, action } = options;
context.resourcer = this;
context.action = this.getAction(resource, action);
return yield context.action.execute(context, next);
});
}
} // action 需要 clone 之后再赋给 ctx
ctx.action = _this.getAction((0, _utils.getNameByParams)(params), params.actionName).clone();
ctx.action.setContext(ctx);
ctx.action.actionName = params.actionName;
ctx.action.resourceOf = params.associatedIndex;
ctx.action.resourceName = params.associatedName ? `${params.associatedName}.${params.resourceName}` : params.resourceName;
ctx.action.params.filterByTk = params.resourceIndex;
const query = (0, _utils.parseQuery)(ctx.request.querystring);
if ((0, _pathToRegexp().pathToRegexp)('/resourcer/{:associatedName.}?:resourceName{\\::actionName}').test(ctx.request.path)) {
ctx.action.mergeParams(_objectSpread(_objectSpread(_objectSpread({}, query), params), ctx.request.body));
} else {
ctx.action.mergeParams(_objectSpread(_objectSpread(_objectSpread({}, query), params), _lodash().default.isEmpty(ctx.request.body) ? {} : {
values: ctx.request.body
}));
}
return (0, _koaCompose().default)(ctx.action.getHandlers())(ctx, next);
} catch (error) {
return next();
}
});
return function restApiMiddleware(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
return restApiMiddleware;
}
middleware(options = {}) {
return this.restApiMiddleware(options);
}
/**
* 实验性 API
*
* @param options
* @param context
* @param next
*/
execute(options, context = {}, next) {
var _this2 = this;
return _asyncToGenerator(function* () {
const resource = options.resource,
action = options.action;
context.resourcer = _this2;
context.action = _this2.getAction(resource, action);
return yield context.action.execute(context, next);
})();
}
}
exports.Resourcer = Resourcer;
exports.default = Resourcer;
//# sourceMappingURL=resourcer.js.map
var _default = Resourcer;
exports.default = _default;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeFields = exports.parseFields = exports.parseQuery = exports.requireModule = exports.parseRequest = exports.getNameByParams = void 0;
const lodash_1 = __importDefault(require("lodash"));
// @ts-ignore
const path_to_regexp_1 = require("path-to-regexp");
const qs_1 = __importDefault(require("qs"));
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getNameByParams = getNameByParams;
exports.mergeFields = mergeFields;
exports.parseFields = parseFields;
exports.parseQuery = parseQuery;
exports.parseRequest = parseRequest;
exports.requireModule = requireModule;
function _lodash() {
const data = _interopRequireDefault(require("lodash"));
_lodash = function _lodash() {
return data;
};
return data;
}
function _pathToRegexp() {
const data = require("path-to-regexp");
_pathToRegexp = function _pathToRegexp() {
return data;
};
return data;
}
function _qs() {
const data = _interopRequireDefault(require("qs"));
_qs = function _qs() {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getNameByParams(params) {
const { resourceName, associatedName } = params;
return associatedName ? `${associatedName}.${resourceName}` : resourceName;
const resourceName = params.resourceName,
associatedName = params.associatedName;
return associatedName ? `${associatedName}.${resourceName}` : resourceName;
}
exports.getNameByParams = getNameByParams;
function parseRequest(request, options = {}) {
const accessors = Object.assign({
// 常规 actions
list: 'list', create: 'create', get: 'get', update: 'update', delete: 'destroy',
// associate 操作
add: 'add', set: 'set', remove: 'remove' }, (options.accessors || {}));
const accessors = _objectSpread({
// 常规 actions
list: 'list',
create: 'create',
get: 'get',
update: 'update',
delete: 'destroy',
// associate 操作
add: 'add',
set: 'set',
remove: 'remove'
}, options.accessors || {});
const keys = [];
const regexp = (0, _pathToRegexp().pathToRegexp)('/resourcer/{:associatedName.}?:resourceName{\\::actionName}', keys);
const matches = regexp.exec(request.path);
if (matches) {
const params = {};
keys.forEach((obj, index) => {
if (matches[index + 1] === undefined) {
return;
}
params[obj.name] = matches[index + 1];
});
return params;
}
const defaults = {
single: {
'/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete
},
'/:resourceName/:resourceIndex': {
get: accessors.get,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete
},
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.create,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete
}
},
hasOne: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.get,
post: accessors.update,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete
}
},
hasMany: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.create,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete
}
},
belongsTo: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.get,
delete: accessors.remove
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
post: accessors.set
}
},
belongsToMany: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.set
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.add,
put: accessors.update,
patch: accessors.update,
delete: accessors.remove
}
}
};
const params = {};
let prefix = (options.prefix || '').trim().replace(/\/$/, '');
if (prefix && !prefix.startsWith('/')) {
prefix = `/${prefix}`;
}
const _request$type = request.type,
type = _request$type === void 0 ? 'single' : _request$type;
for (const path in defaults[type]) {
const keys = [];
const regexp = (0, path_to_regexp_1.pathToRegexp)('/resourcer/{:associatedName.}?:resourceName{\\::actionName}', keys);
const regexp = (0, _pathToRegexp().pathToRegexp)(`${prefix}${path}`, keys, {});
const matches = regexp.exec(request.path);
if (matches) {
const params = {};
keys.forEach((obj, index) => {
if (matches[index + 1] === undefined) {
return;
}
params[obj.name] = matches[index + 1];
});
return params;
if (!matches) {
continue;
}
const defaults = {
single: {
'/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete,
},
'/:resourceName/:resourceIndex': {
get: accessors.get,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete,
},
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete,
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.create,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete,
},
},
hasOne: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.get,
post: accessors.update,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete,
},
},
hasMany: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.create,
delete: accessors.delete,
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.create,
put: accessors.update,
patch: accessors.update,
delete: accessors.delete,
},
},
belongsTo: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.get,
delete: accessors.remove,
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
post: accessors.set,
},
},
belongsToMany: {
'/:associatedName/:associatedIndex/:resourceName': {
get: accessors.list,
post: accessors.set,
},
'/:associatedName/:associatedIndex/:resourceName/:resourceIndex': {
get: accessors.get,
post: accessors.add,
put: accessors.update,
patch: accessors.update,
delete: accessors.remove,
},
},
};
const params = {};
let prefix = (options.prefix || '').trim().replace(/\/$/, '');
if (prefix && !prefix.startsWith('/')) {
prefix = `/${prefix}`;
keys.forEach((obj, index) => {
if (matches[index + 1] === undefined) {
return;
}
params[obj.name] = matches[index + 1];
});
params.actionName = _lodash().default.get(defaults, [type, path, request.method.toLowerCase()]);
}
if (Object.keys(params).length === 0) {
return false;
}
if (params.resourceName) {
const _params$resourceName$ = params.resourceName.split(':'),
_params$resourceName$2 = _slicedToArray(_params$resourceName$, 2),
resourceName = _params$resourceName$2[0],
actionName = _params$resourceName$2[1];
if (actionName) {
params.resourceName = resourceName;
params.actionName = actionName;
}
const { type = 'single' } = request;
for (const path in defaults[type]) {
const keys = [];
const regexp = (0, path_to_regexp_1.pathToRegexp)(`${prefix}${path}`, keys, {});
const matches = regexp.exec(request.path);
if (!matches) {
continue;
}
keys.forEach((obj, index) => {
if (matches[index + 1] === undefined) {
return;
}
params[obj.name] = matches[index + 1];
});
params.actionName = lodash_1.default.get(defaults, [type, path, request.method.toLowerCase()]);
}
if (Object.keys(params).length === 0) {
return false;
}
if (params.resourceName) {
const [resourceName, actionName] = params.resourceName.split(':');
if (actionName) {
params.resourceName = resourceName;
params.actionName = actionName;
}
}
return params;
}
return params;
}
exports.parseRequest = parseRequest;
function requireModule(module) {
if (typeof module === 'string') {
module = require(module);
}
if (typeof module !== 'object') {
return module;
}
return module.__esModule ? module.default : module;
if (typeof module === 'string') {
module = require(module);
}
if (typeof module !== 'object') {
return module;
}
return module.__esModule ? module.default : module;
}
exports.requireModule = requireModule;
function parseQuery(input) {
// 自带 query 处理的不太给力,需要用 qs 转一下
const query = qs_1.default.parse(input, {
// 原始 query string 中如果一个键连等号“=”都没有可以被认为是 null 类型
strictNullHandling: true,
// 逗号分隔转换为数组
// comma: true,
});
// filter 支持 json string
if (typeof query.filter === 'string') {
query.filter = JSON.parse(query.filter);
}
return query;
// 自带 query 处理的不太给力,需要用 qs 转一下
const query = _qs().default.parse(input, {
// 原始 query string 中如果一个键连等号“=”都没有可以被认为是 null 类型
strictNullHandling: true // 逗号分隔转换为数组
// comma: true,
}); // filter 支持 json string
if (typeof query.filter === 'string') {
query.filter = JSON.parse(query.filter);
}
return query;
}
exports.parseQuery = parseQuery;
function parseFields(fields) {
if (!fields) {
return {};
}
if (typeof fields === 'string') {
fields = fields.split(',').map((field) => field.trim());
}
if (Array.isArray(fields)) {
const onlyFields = [];
const output = {};
fields.forEach((item) => {
if (typeof item === 'string') {
onlyFields.push(item);
}
else if (typeof item === 'object') {
if (item.only) {
onlyFields.push(...item.only.toString().split(','));
}
Object.assign(output, parseFields(item));
}
});
if (onlyFields.length) {
output.only = onlyFields;
if (!fields) {
return {};
}
if (typeof fields === 'string') {
fields = fields.split(',').map(field => field.trim());
}
if (Array.isArray(fields)) {
const onlyFields = [];
const output = {};
fields.forEach(item => {
if (typeof item === 'string') {
onlyFields.push(item);
} else if (typeof item === 'object') {
if (item.only) {
onlyFields.push(...item.only.toString().split(','));
}
return output;
Object.assign(output, parseFields(item));
}
});
if (onlyFields.length) {
output.only = onlyFields;
}
if (fields.only && typeof fields.only === 'string') {
fields.only = fields.only.split(',').map((field) => field.trim());
}
if (fields.except && typeof fields.except === 'string') {
fields.except = fields.except.split(',').map((field) => field.trim());
}
if (fields.appends && typeof fields.appends === 'string') {
fields.appends = fields.appends.split(',').map((field) => field.trim());
}
return fields;
return output;
}
if (fields.only && typeof fields.only === 'string') {
fields.only = fields.only.split(',').map(field => field.trim());
}
if (fields.except && typeof fields.except === 'string') {
fields.except = fields.except.split(',').map(field => field.trim());
}
if (fields.appends && typeof fields.appends === 'string') {
fields.appends = fields.appends.split(',').map(field => field.trim());
}
return fields;
}
exports.parseFields = parseFields;
function mergeFields(defaults, inputs) {
let fields = {};
defaults = parseFields(defaults);
inputs = parseFields(inputs);
if (inputs.only) {
// 前端提供 only,后端提供 only
if (defaults.only) {
fields.only = defaults.only.filter((field) => inputs.only.includes(field));
}
// 前端提供 only,后端提供 except,输出 only 排除 except
else if (defaults.except) {
fields.only = inputs.only.filter((field) => !defaults.except.includes(field));
}
// 前端提供 only,后端没有提供 only 或 except
else {
fields.only = inputs.only;
}
let fields = {};
defaults = parseFields(defaults);
inputs = parseFields(inputs);
if (inputs.only) {
// 前端提供 only,后端提供 only
if (defaults.only) {
fields.only = defaults.only.filter(field => inputs.only.includes(field));
} // 前端提供 only,后端提供 except,输出 only 排除 except
else if (defaults.except) {
fields.only = inputs.only.filter(field => !defaults.except.includes(field));
} // 前端提供 only,后端没有提供 only 或 except
else {
fields.only = inputs.only;
}
else if (inputs.except) {
// 前端提供 except,后端提供 only,只输出 only 里排除 except 的字段
if (defaults.only) {
fields.only = defaults.only.filter((field) => !inputs.except.includes(field));
}
// 前端提供 except,后端提供 except 或不提供,合并 except
else {
fields.except = lodash_1.default.uniq([...inputs.except, ...(defaults.except || [])]);
}
}
// 前端没提供 only 或 except
} else if (inputs.except) {
// 前端提供 except,后端提供 only,只输出 only 里排除 except 的字段
if (defaults.only) {
fields.only = defaults.only.filter(field => !inputs.except.includes(field));
} // 前端提供 except,后端提供 except 或不提供,合并 except
else {
fields = defaults;
fields.except = _lodash().default.uniq([...inputs.except, ...(defaults.except || [])]);
}
// 如果前端提供了 appends
if (!lodash_1.default.isEmpty(inputs.appends)) {
fields.appends = lodash_1.default.uniq([...inputs.appends, ...(defaults.appends || [])]);
}
if (!fields.appends) {
fields.appends = [];
}
return fields;
}
exports.mergeFields = mergeFields;
//# sourceMappingURL=utils.js.map
} // 前端没提供 only 或 except
else {
fields = defaults;
} // 如果前端提供了 appends
if (!_lodash().default.isEmpty(inputs.appends)) {
fields.appends = _lodash().default.uniq([...inputs.appends, ...(defaults.appends || [])]);
}
if (!fields.appends) {
fields.appends = [];
}
return fields;
}
{
"name": "@nocobase/resourcer",
"version": "0.7.0-alpha.34",
"version": "0.7.0-alpha.56",
"description": "",

@@ -14,7 +14,2 @@ "main": "./lib/index.js",

],
"scripts": {
"build": "rimraf -rf lib esm dist && npm run build:cjs && npm run build:esm",
"build:cjs": "tsc --project tsconfig.build.json",
"build:esm": "tsc --project tsconfig.build.json --module es2015 --outDir esm"
},
"dependencies": {

@@ -32,3 +27,3 @@ "deepmerge": "^4.2.2",

},
"gitHead": "48b2b4bc7bbc39533e461d34d7f026a4ad1a9b5c"
"gitHead": "9a8c05e8fb26029f1d1ba68408a8bddac0e67a76"
}
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