UNPKG

2.3 kBJavaScriptView Raw
1// Copyright © 2017 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16const debug = require('debug')('cloudant:plugins:base');
17const lockFile = require('lockfile');
18const tmp = require('tmp');
19
20function noop() {}
21
22/**
23 * Cloudant base plugin.
24 *
25 * @param {Object} client - HTTP client.
26 * @param {Object} cfg - Client configuration.
27 */
28class BasePlugin {
29 constructor(client, cfg) {
30 this._client = client;
31 this._cfg = cfg;
32 this._disabled = false;
33 this._lockFile = tmp.tmpNameSync({ postfix: '.lock' });
34 }
35
36 get id() {
37 return this.constructor.id;
38 }
39
40 get disabled() {
41 return this._disabled;
42 }
43
44 // Disable a plugin to prevent all hooks from being executed.
45 set disabled(disabled) {
46 this._disabled = disabled;
47 }
48
49 // NOOP Base Hooks
50
51 onRequest(state, request, callback) {
52 callback(state);
53 }
54
55 onResponse(state, response, callback) {
56 callback(state);
57 }
58
59 onError(state, error, callback) {
60 callback(state);
61 }
62
63 // Helpers
64
65 // Acquire a file lock on the specified path. Release the file lock on
66 // completion of the callback.
67 withLock(opts, callback) {
68 var self = this;
69 if (typeof opts === 'function') {
70 callback = opts;
71 opts = {};
72 }
73 debug('Acquiring lock...');
74 lockFile.lock(self._lockFile, opts, function(error) {
75 if (error) {
76 callback(error, noop);
77 } else {
78 callback(null, function() {
79 // Close and unlink the file lock.
80 lockFile.unlock(self._lockFile, function(error) {
81 if (error) {
82 debug(`Failed to release lock: ${error}`);
83 }
84 });
85 });
86 }
87 });
88 }
89}
90
91BasePlugin.id = 'base';
92BasePlugin.pluginVersion = 2;
93
94module.exports = BasePlugin;