(name, method, options, realm)
| 38 | } |
| 39 | |
| 40 | _add(name, method, options, realm) { |
| 41 | |
| 42 | Hoek.assert(typeof method === 'function', 'method must be a function'); |
| 43 | Hoek.assert(typeof name === 'string', 'name must be a string'); |
| 44 | Hoek.assert(name.match(internals.methodNameRx), 'Invalid name:', name); |
| 45 | Hoek.assert(!Hoek.reach(this.methods, name, { functions: false }), 'Server method function name already exists:', name); |
| 46 | |
| 47 | options = Config.apply('method', options, name); |
| 48 | |
| 49 | const settings = Hoek.clone(options, { shallow: ['bind'] }); |
| 50 | settings.generateKey = settings.generateKey ?? internals.generateKey; |
| 51 | |
| 52 | const bind = settings.bind ?? realm.settings.bind ?? null; |
| 53 | const bound = !bind ? method : (...args) => method.apply(bind, args); |
| 54 | |
| 55 | // Not cached |
| 56 | |
| 57 | if (!settings.cache) { |
| 58 | return this._assign(name, bound); |
| 59 | } |
| 60 | |
| 61 | // Cached |
| 62 | |
| 63 | Hoek.assert(!settings.cache.generateFunc, 'Cannot set generateFunc with method caching:', name); |
| 64 | Hoek.assert(settings.cache.generateTimeout !== undefined, 'Method caching requires a timeout value in generateTimeout:', name); |
| 65 | |
| 66 | settings.cache.generateFunc = (id, flags) => bound(...id.args, flags); |
| 67 | const cache = this.#core._cachePolicy(settings.cache, '#' + name); |
| 68 | |
| 69 | const func = function (...args) { |
| 70 | |
| 71 | const key = settings.generateKey.apply(bind, args); |
| 72 | if (typeof key !== 'string') { |
| 73 | return Promise.reject(Boom.badImplementation('Invalid method key when invoking: ' + name, { name, args })); |
| 74 | } |
| 75 | |
| 76 | return cache.get({ id: key, args }); |
| 77 | }; |
| 78 | |
| 79 | func.cache = { |
| 80 | drop: function (...args) { |
| 81 | |
| 82 | const key = settings.generateKey.apply(bind, args); |
| 83 | if (typeof key !== 'string') { |
| 84 | return Promise.reject(Boom.badImplementation('Invalid method key when invoking: ' + name, { name, args })); |
| 85 | } |
| 86 | |
| 87 | return cache.drop(key); |
| 88 | }, |
| 89 | stats: cache.stats |
| 90 | }; |
| 91 | |
| 92 | this._assign(name, func, func); |
| 93 | } |
| 94 | |
| 95 | _assign(name, method) { |
| 96 |
no test coverage detected