Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

160 rindas
2.3 KiB

  1. const serverConfig = require('../config/serverConfig');
  2. const tableNames = require('./tableNames');
  3. const r = require('rethinkdbdash')({
  4. host: serverConfig.dbHost,
  5. port: serverConfig.dbPort,
  6. db: serverConfig.dbName
  7. });
  8. module.exports = {
  9. staticCon: null,
  10. init: async function (cbReady) {
  11. await this.create();
  12. cbReady();
  13. },
  14. create: async function () {
  15. try {
  16. await r.dbCreate(this.useDb).run();
  17. } catch (e) {
  18. }
  19. for (const table of tableNames) {
  20. try {
  21. await r.tableCreate(table).run();
  22. } catch (e) {
  23. if (!e.message.includes('already exists'))
  24. _.log(e);
  25. }
  26. }
  27. },
  28. getAsync: async function ({
  29. table,
  30. key,
  31. isArray,
  32. noDefault
  33. }) {
  34. let res = await r.table(table)
  35. .get(key)
  36. .run();
  37. if (res)
  38. return res.value;
  39. else if (isArray && !noDefault)
  40. return [];
  41. return res;
  42. },
  43. getAllAsync: async function ({
  44. table,
  45. key,
  46. isArray,
  47. noDefault
  48. }) {
  49. let res = await r.table(table)
  50. .run();
  51. if (res)
  52. return res;
  53. else if (isArray && !noDefault)
  54. return [];
  55. return res;
  56. },
  57. setAsync: async function ({
  58. table,
  59. key: id,
  60. value,
  61. conflict = 'update'
  62. }) {
  63. try {
  64. await r.table(table)
  65. .insert({
  66. id,
  67. value
  68. }, {
  69. conflict
  70. })
  71. .run();
  72. } catch (e) {
  73. this.logError(e, table, id);
  74. }
  75. },
  76. deleteAsync: async function ({
  77. key,
  78. table
  79. }) {
  80. await r.table(table)
  81. .get(key)
  82. .delete()
  83. .run();
  84. },
  85. subscribe: function (table) {
  86. return r.table(table)
  87. .changes()
  88. .run();
  89. },
  90. append: async function ({
  91. table,
  92. key,
  93. value,
  94. field
  95. }) {
  96. try {
  97. await r.table(table)
  98. .get(key)
  99. .update(row => {
  100. return r.branch(
  101. row('value').typeOf().eq('ARRAY'),
  102. {
  103. [field]: row('value').setUnion(value)
  104. },
  105. {
  106. [field]: value
  107. }
  108. );
  109. })
  110. .run();
  111. } catch (e) {
  112. this.logError(e, table, key);
  113. }
  114. },
  115. exists: async function ({
  116. table,
  117. key
  118. }) {
  119. let res = await r.table(table)
  120. .get(key)
  121. .run();
  122. return !!res;
  123. },
  124. logError: async function (error, table, key) {
  125. try {
  126. const errorValue = `${error.toString()} | ${error.stack.toString()} | ${table} | ${key}`;
  127. await this.setAsync({
  128. key: new Date(),
  129. table: 'error',
  130. value: errorValue
  131. });
  132. } catch (e) {}
  133. process.send({
  134. event: 'onCrashed'
  135. });
  136. }
  137. };