cache.controller.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /* Copyright (C) 2020, 2019 Girish M
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2 of the License, or
  5. * (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software
  14. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  15. * MA 02110-1301, USA.
  16. *
  17. */
  18. const Cache = require('./cache.model.js');
  19. const max_cached_items = 10;
  20. function randomData(length) {
  21. let result = '';
  22. let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  23. let charactersLength = characters.length;
  24. for (let i = 0; i < length; i++) {
  25. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  26. }
  27. return result;
  28. }
  29. function createCacheEntry(req, res) {
  30. Cache.count({}, (err, count) => {
  31. if (!err) {
  32. console.log("Keys in cache: ", count);
  33. cacheKey = req.body.key || req.params.key;
  34. if (count <= max_cached_items) {
  35. if (cacheKey) {
  36. Cache.findOne({ key: cacheKey }).then(cache => {
  37. if (!cache) {
  38. console.log("Key not found in cache. Creating new entry.");
  39. const cache = new Cache({
  40. key: cacheKey,
  41. data: randomData((Math.random() * 10) + 1), //random data with random length between 1 and 10
  42. ttl: Math.floor((Math.random() * 100) + 1) //ttl is a random number between 1 and 100 minutes.
  43. });
  44. cache.save().then(data => {
  45. console.log("Created new cache entry ", data);
  46. res.send(cache.data);
  47. }).catch(err => {
  48. return res.status(500).send({
  49. message: err.message || "Something wrong while creating cache entry."
  50. })
  51. })
  52. }
  53. else {
  54. console.log("Updating cache entry for key: " + cacheKey);
  55. return res.send(cache);
  56. }
  57. }).catch(err => {
  58. if (err.kind === 'ObjectId') {
  59. return res.status(404).send({
  60. message: "Cache entry not found with key " + cacheKey
  61. });
  62. }
  63. return res.status(500).send({
  64. message: "Something wrong updating cache with key " + cacheKey
  65. });
  66. });
  67. }
  68. }
  69. else {
  70. //replace the cache item with shortest ttl
  71. console.log("Replacing the oldest cached item");
  72. const replacementCache = {
  73. key: cacheKey,
  74. data: randomData((Math.random() * 10) + 1), //random data with random length between 1 and 10
  75. ttl: Math.floor((Math.random() * 100) + 1), //ttl is a random number between 1 and 100 minutes.
  76. createdAt: new Date().toISOString(),
  77. updatedAt: new Date().toISOString()
  78. };
  79. Cache.findOneAndReplace({"ttl":{$gt : 0}}, replacementCache, {sort: {"updatedAt": 1}}).then(data => {
  80. console.log("Created replacement entry ", data);
  81. res.send(replacementCache.data);
  82. }).catch(err => {
  83. if (err.kind === 'ObjectId') {
  84. return res.status(404).send({
  85. message: "Cache entry not found with key " + cacheKey
  86. });
  87. }
  88. return res.status(500).send({
  89. message: "Something wrong updating cache with key " + cacheKey
  90. });
  91. });
  92. }
  93. }
  94. else{
  95. console.log(err);
  96. res.status(500).send({
  97. message: "Some error occurred while getting key count"
  98. })
  99. }
  100. });
  101. }
  102. exports.create = (req, res) => {
  103. if (!req.body) {
  104. return res.status(400).send({
  105. message: "Cache content cannot be empty"
  106. });
  107. }
  108. if (req.body.key) {
  109. return createCacheEntry(req, res);
  110. }
  111. else {
  112. return res.status(400).send({
  113. message: "Key cannot be empty"
  114. });
  115. }
  116. }
  117. exports.findAll = (req, res) => {
  118. Cache.find().then(cache => {
  119. res.send(cache);
  120. }).catch(err => {
  121. res.status(500).send({
  122. message: err.message || "Something wrong while creating cache entry."
  123. })
  124. })
  125. }
  126. exports.findOne = (req, res) => {
  127. Cache.findOne({ key: req.params.key })
  128. .then(cache => {
  129. if (!cache) {
  130. console.log("Cache miss");
  131. createCacheEntry(req, res);
  132. }
  133. else {
  134. console.log("Cache hit");
  135. res.send(cache.data);
  136. }
  137. }).catch(err => {
  138. if (err.kind === 'ObjectId') {
  139. return res.status(404).send({
  140. message: "Cache not found with id " + req.params.key
  141. });
  142. }
  143. return res.status(500).send({
  144. message: "Something wrong retrieving cache with id " + req.params.key
  145. });
  146. });
  147. };
  148. exports.delete = (req, res) => {
  149. Cache.findOneAndRemove({ key: req.params.key })
  150. .then(cache => {
  151. if (!cache) {
  152. return res.status(404).send({
  153. message: "Cache miss, key: " + req.params.key + " not found."
  154. });
  155. }
  156. return res.send({ message: "Key removed from cache!" });
  157. }).catch(err => {
  158. if (err.kind === 'ObjectId' || err.name === 'NotFound') {
  159. return res.status(404).send({
  160. message: "Key not found with id " + req.params.key
  161. });
  162. }
  163. return res.status(500).send({
  164. message: "Could not delete key with id " + req.params.key
  165. });
  166. });
  167. }
  168. exports.deleteAll = (req, res) => {
  169. Cache.deleteMany().then(result => {
  170. if (!result) {
  171. return res.status(404).send({
  172. message: "Couldn't delete all keys."
  173. });
  174. }
  175. return res.send({ message: "All keys removed from the cache." });
  176. }).catch(err => {
  177. return res.status(500).send({
  178. message: "Error occured while deleting keys: " + err
  179. })
  180. })
  181. }