Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

237 linhas
5.0 KiB

  1. let util = require('util');
  2. const tableNames = require('./tableNames');
  3. module.exports = {
  4. db: null,
  5. file: '../../data/storage.db',
  6. buffer: [],
  7. processing: [],
  8. tables: {},
  9. init: async function (cbReady) {
  10. let sqlite = require('sqlite3').verbose();
  11. this.db = new sqlite.Database(this.file, this.onDbCreated.bind(this, cbReady));
  12. },
  13. onDbCreated: function (cbReady) {
  14. let db = this.db;
  15. let scope = this;
  16. db.serialize(function () {
  17. for (let t in tableNames) {
  18. db.run(`
  19. CREATE TABLE ${t} (key VARCHAR(50), value TEXT)
  20. `, scope.onTableCreated.bind(scope, t));
  21. }
  22. cbReady();
  23. }, this);
  24. },
  25. onTableCreated: async function (table) {
  26. },
  27. //ent, field
  28. get: function (options) {
  29. let key = options.ent;
  30. let table = options.field;
  31. options.query = `SELECT * FROM ${table} WHERE key = '${key}' LIMIT 1`;
  32. this.db.get(options.query, this.done.bind(this, options));
  33. },
  34. getAsync: async function (options) {
  35. return await this.queue({
  36. type: 'get',
  37. options: options
  38. });
  39. },
  40. getAllAsync: async function (options) {
  41. return await this.queue({
  42. type: 'getAll',
  43. options: options
  44. });
  45. },
  46. delete: function (options) {
  47. let key = options.ent;
  48. let table = options.field;
  49. options.query = `DELETE FROM ${table} WHERE key = '${key}'`;
  50. this.db.run(options.query, this.done.bind(this, options));
  51. },
  52. deleteAsync: async function (options) {
  53. await this.queue({
  54. type: 'delete',
  55. options: options
  56. });
  57. },
  58. //ent, field, value
  59. set: function (options) {
  60. let key = options.ent;
  61. let table = options.field;
  62. this.db.get(`SELECT 1 FROM ${table} where key = '${key}'`, this.doesExist.bind(this, options));
  63. },
  64. doesExist: function (options, err, result) {
  65. let key = options.ent;
  66. let table = options.field;
  67. let query = `INSERT INTO ${table} (key, value) VALUES('${key}', '${options.value}')`;
  68. if (result)
  69. query = `UPDATE ${table} SET value = '${options.value}' WHERE key = '${key}'`;
  70. this.db.run(query, this.done.bind(this, options));
  71. },
  72. setAsync: async function (options) {
  73. await this.queue({
  74. type: 'set',
  75. options: options
  76. });
  77. },
  78. queue: async function (config) {
  79. let resolve = null;
  80. let promise = new Promise(function (res) {
  81. resolve = res;
  82. });
  83. this.buffer.push({
  84. resolve: resolve,
  85. config: config
  86. });
  87. this.process();
  88. return promise;
  89. },
  90. process: async function () {
  91. let next = this.buffer.splice(0, 1);
  92. if (!next.length)
  93. return;
  94. next = next[0];
  95. let config = next.config;
  96. let options = config.options;
  97. let res = null;
  98. try {
  99. if (config.type === 'get')
  100. res = await this.processGet(options);
  101. else if (config.type === 'getAll')
  102. res = await this.processGetAll(options);
  103. else if (config.type === 'set')
  104. await this.processSet(options);
  105. else if (config.type === 'delete')
  106. await this.processDelete(options);
  107. } catch (e) {
  108. if (e.toString().indexOf('unrecognized token') > -1)
  109. _.log(e);
  110. _.log(e);
  111. this.buffer.splice(0, 0, next);
  112. setTimeout(this.process.bind(this), 10);
  113. return;
  114. }
  115. next.resolve(res);
  116. setTimeout(this.process.bind(this), 10);
  117. },
  118. processGet: async function (options) {
  119. let res = await util.promisify(this.db.get.bind(this.db))(`SELECT * FROM ${options.table} WHERE key = '${options.key}' LIMIT 1`);
  120. if (res) {
  121. res = res.value;
  122. if (options.clean) {
  123. res = res
  124. .split('`')
  125. .join('\'')
  126. .replace(/''+/g, '\'');
  127. }
  128. if (!options.noParse)
  129. res = JSON.parse(res);
  130. } else if (!options.noParse && !options.noDefault)
  131. res = options.isArray ? [] : {};
  132. return res;
  133. },
  134. processGetAll: async function (options) {
  135. let res = await util.promisify(this.db.all.bind(this.db))(`SELECT * FROM ${options.table}`);
  136. if (res) {
  137. if (options.clean) {
  138. res.forEach(r => {
  139. r.value = r.value
  140. .split('`')
  141. .join('\'')
  142. .replace(/''+/g, '\'');
  143. });
  144. }
  145. if (!options.noParse) {
  146. if (!res)
  147. res = options.isArray ? [] : {};
  148. else {
  149. res.forEach(r => {
  150. r.value = JSON.parse(r.value);
  151. });
  152. }
  153. }
  154. } else if (!options.noParse && !options.noDefault)
  155. res = options.isArray ? [] : {};
  156. return res;
  157. },
  158. processSet: async function (options) {
  159. let table = options.table;
  160. let key = options.key;
  161. let value = options.value;
  162. if (options.serialize)
  163. value = JSON.stringify(value);
  164. let exists = await util.promisify(this.db.get.bind(this.db))(`SELECT * FROM ${table} WHERE key = '${key}' LIMIT 1`);
  165. let query = `INSERT INTO ${table} (key, value) VALUES('${key}', '${value}')`;
  166. if (exists)
  167. query = `UPDATE ${table} SET value = '${value}' WHERE key = '${key}'`;
  168. await util.promisify(this.db.run.bind(this.db))(query);
  169. },
  170. processDelete: async function (options) {
  171. let table = options.table;
  172. let key = options.key;
  173. let query = `DELETE FROM ${table} WHERE key = '${key}'`;
  174. await util.promisify(this.db.run.bind(this.db))(query);
  175. },
  176. done: function (options, err, result) {
  177. result = result || {
  178. value: null
  179. };
  180. if (options.callback)
  181. options.callback(result.value);
  182. }
  183. };