UNPKG

2.61 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2019,2020. All Rights Reserved.
3// Node module: @loopback/context
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.createProxyWithInterceptors = exports.InterceptionHandler = exports.ProxySource = void 0;
8const context_1 = require("./context");
9const interceptor_1 = require("./interceptor");
10const resolution_session_1 = require("./resolution-session");
11/**
12 * Invocation source for injected proxies. It wraps a snapshot of the
13 * `ResolutionSession` that tracks the binding/injection stack.
14 */
15class ProxySource {
16 constructor(value) {
17 this.value = value;
18 this.type = 'proxy';
19 }
20 toString() {
21 return this.value.getBindingPath();
22 }
23}
24exports.ProxySource = ProxySource;
25/**
26 * A proxy handler that applies interceptors
27 *
28 * See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
29 */
30class InterceptionHandler {
31 constructor(context = new context_1.Context(), session, source) {
32 this.context = context;
33 this.session = session;
34 this.source = source;
35 }
36 get(target, propertyName, receiver) {
37 // eslint-disable-next-line @typescript-eslint/no-explicit-any
38 const targetObj = target;
39 if (typeof propertyName !== 'string')
40 return targetObj[propertyName];
41 const propertyOrMethod = targetObj[propertyName];
42 if (typeof propertyOrMethod === 'function') {
43 return (...args) => {
44 var _a;
45 return (0, interceptor_1.invokeMethodWithInterceptors)(this.context, target, propertyName, args, {
46 source: (_a = this.source) !== null && _a !== void 0 ? _a : (this.session && new ProxySource(this.session)),
47 });
48 };
49 }
50 else {
51 return propertyOrMethod;
52 }
53 }
54}
55exports.InterceptionHandler = InterceptionHandler;
56/**
57 * Create a proxy that applies interceptors for method invocations
58 * @param target - Target class or object
59 * @param context - Context object
60 * @param session - Resolution session
61 * @param source - Invocation source
62 */
63function createProxyWithInterceptors(target, context, session, source) {
64 return new Proxy(target, new InterceptionHandler(context, resolution_session_1.ResolutionSession.fork(session), source));
65}
66exports.createProxyWithInterceptors = createProxyWithInterceptors;
67//# sourceMappingURL=interception-proxy.js.map
\No newline at end of file