UNPKG

3.11 kBJavaScriptView Raw
1"use strict";
2/*
3 * @adonisjs/sink
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10Object.defineProperty(exports, "__esModule", { value: true });
11exports.KeyValuePair = void 0;
12const File_1 = require("./File");
13/**
14 * Exposes the API to work with key/value pair files like `ini`, `yaml`
15 * and `json`.
16 */
17class KeyValuePair extends File_1.File {
18 constructor(basePath) {
19 super(basePath);
20 this.actions = [];
21 }
22 /**
23 * Set key/value pair
24 */
25 set(key, value) {
26 this.addAction('set', { key, value });
27 return this;
28 }
29 /**
30 * Unset key/value pair
31 */
32 unset(key) {
33 this.addAction('unset', { key });
34 return this;
35 }
36 /**
37 * Remove file
38 */
39 delete() {
40 this.addAction('delete');
41 return this;
42 }
43 get(address, defaultValue) {
44 return address ? this.filePointer.get(address, defaultValue) : this.filePointer.get();
45 }
46 /**
47 * A boolean telling if the file already exists
48 */
49 exists() {
50 return this.filePointer.exists();
51 }
52 /**
53 * Commit mutations
54 */
55 commit() {
56 this.cdIn();
57 const actions = this.getCommitActions();
58 const deleteFile = actions.find(({ action }) => action === 'delete');
59 /**
60 * In case of `delete` action. There is no point running
61 * other actions and we can simply delete the file
62 */
63 if (deleteFile) {
64 this.filePointer.delete();
65 this.cdOut();
66 return;
67 }
68 actions.forEach(({ action, body }) => {
69 if (typeof this[`on${action}`] === 'function') {
70 const handled = this[`on${action}`]('commit', body);
71 /**
72 * Return early when action is handled by the hook
73 */
74 if (handled) {
75 return;
76 }
77 }
78 if (action === 'set') {
79 this.filePointer.set(body.key, body.value);
80 return;
81 }
82 if (action === 'unset') {
83 this.filePointer.unset(body.key);
84 }
85 });
86 this.filePointer.save();
87 this.cdOut();
88 }
89 /**
90 * Rollback mutations
91 */
92 rollback() {
93 this.cdIn();
94 const actions = this.getRevertActions();
95 actions.forEach(({ action, body }) => {
96 if (typeof this[`on${action}`] === 'function') {
97 const handled = this[`on${action}`]('rollback', body);
98 /**
99 * Return early when action is handled by the hook
100 */
101 if (handled) {
102 return;
103 }
104 }
105 if (action === 'set') {
106 this.filePointer.unset(body.key);
107 return;
108 }
109 });
110 this.filePointer.save();
111 this.cdOut();
112 }
113}
114exports.KeyValuePair = KeyValuePair;