{"id":20560435,"url":"https://github.com/vodolaz095/express-view-cache","last_synced_at":"2025-04-14T14:04:53.838Z","repository":{"id":8651556,"uuid":"10303381","full_name":"vodolaz095/express-view-cache","owner":"vodolaz095","description":"Unobtrusive solution to express framework - cache rendered page, without database requests and rendering.","archived":false,"fork":false,"pushed_at":"2022-12-14T13:03:36.000Z","size":169,"stargazers_count":20,"open_issues_count":5,"forks_count":16,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-29T05:19:18.962Z","etag":null,"topics":["cache","express","middleware","nodejs","redis"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vodolaz095.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-05-26T20:48:11.000Z","updated_at":"2021-11-03T10:48:39.000Z","dependencies_parsed_at":"2023-01-11T17:26:30.497Z","dependency_job_id":null,"html_url":"https://github.com/vodolaz095/express-view-cache","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fexpress-view-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fexpress-view-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fexpress-view-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vodolaz095%2Fexpress-view-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vodolaz095","download_url":"https://codeload.github.com/vodolaz095/express-view-cache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224873081,"owners_count":17384078,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","express","middleware","nodejs","redis"],"created_at":"2024-11-16T03:54:32.861Z","updated_at":"2024-11-16T03:54:33.519Z","avatar_url":"https://github.com/vodolaz095.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"express-view-cache\n==================\n[![NPM version](https://badge.fury.io/js/express-view-cache.svg)](http://badge.fury.io/js/express-view-cache)\n[![Build Status](https://travis-ci.org/vodolaz095/express-view-cache.png)](https://travis-ci.org/vodolaz095/express-view-cache)\n\nUnobtrusive solution to express 4.0.0 framework - cache response content in Redis database.\n\nShameless advertisement\n==================\nYou can hire the author of this package by Upwork - [https://www.upwork.com/freelancers/~0120ba573d09c66c51](https://www.upwork.com/freelancers/~0120ba573d09c66c51/)\n\n\nWhy do we need this plugin and how does it work?\n==================\n\nLet's consider we have a NodeJS application with code like this:\n\n    app.get('/getPopularPosts',function(req,res){\n        req.model.posts.getPopular(function(err,posts){\n            if(err) throw err;\n            res.render('posts',{\"posts\":posts});\n        });\n    });\n\nThe method `getPopular` of `posts` requires a call to database and executed slowly. Also rendering the template of posts\nrequires some time. So, maybe we need to cache all this? Ideally, when visitor gets the page with url  `/getPopularPosts`\nwe have to give him info right from cache, without requests to database, parsing data received, rendering page and other things\nwe need to do to give him this page. The most expressJS way to do it is to make a separate middleware, that is ran before\nrouter middleware, and returns page from cache (if it is present in cache) or pass data to other middlewares, but this caching\nmiddleware adds a listener to response, which SAVES rendered response to cache. And for future use, the response is taken from CACHE!\n\nIt is turned that it works best with [node-redis](https://github.com/mranney/node_redis) with [redis](http://redis.io) \u003ev2.6.16\n\n\n\nExample\n==================\nThere is a complete example of NodeJS + ExpressJS (4.x.x) application which responds with current time.\n\n```javascript\n\n'use strict';\n\nconst express = require('express');\nconst  morgan = require('morgan');\nconst  errorHandler = require('errorhandler');\nconst  request = require('request');\nconst  http = require('http');\nconst  EVC = require('./../');\nconst  app = express();\nconst  evc = EVC('redis://redis:someLongAuthPassword@localhost:6379');\n\napp.set('port', process.env.PORT || 3000);\napp.use(morgan('dev'));\n\n// simple caching middlewared\napp.use('/cacheFor5sec', evc.cachingMiddleware(5000)); // every path with prefix /cacheFor5sec is cached for 5 seconds\napp.use('/cacheFor3sec', evc.cachingMiddleware(3000)); // every path with prefix /cacheFor3sec is cached for 3 seconds\n\n// every path with /cacheCustom will be cached with key based on users IP  and ttl 3 seconds\napp.use('/cacheCustom', evc.customCachingMiddleware(function (req, cb){\n  return process.nextTick(function (){\n    cb(null, `${req.ip}`, 3000);\n  });\n}));\n\napp.get('*', function (request, response) {\n  response.json({\n    'Page Created At': new Date().toLocaleTimeString()\n  });\n});\napp.use(errorHandler());\n\nhttp.createServer(app).listen(app.get('port'), function () {\n  console.log('Express server listening on port %s', app.get('port')); // eslint-disable-line\n  setInterval(function(){\n    request('http://localhost:'+app.get('port')+'/', function(error, response, body){\n      console.log('GET /',body);  // eslint-disable-line\n    });\n  }, 1000);\n  setInterval(function(){\n    request('http://localhost:'+app.get('port')+'/cacheFor3sec', function(error, response, body){\n      console.log('GET /cacheFor3sec',body);  // eslint-disable-line\n    });\n  }, 1000);\n  setInterval(function(){\n    request('http://localhost:'+app.get('port')+'/cacheCustom', function(error, response, body){\n      console.log('GET /cacheCustom',body);  // eslint-disable-line\n    });\n  }, 1000);\n});\n\n\n```\n\n\nOptions\n==================\n\n    const evc = EVC(options);\n\n`Options` can be a redis connection string like `redis://usernameTotallyIgnored:someLongPassword@redis.example.org:6379`\n\nalso `options` can be a dictionary object with these fields:\n\n* `host` - default is `localhost` - the hostname of redis server\n* `port` - default is `6379` - the port where the redis server listens\n* `pass` - password for redis authorization, default is null\n* `client` - ready to use [node-redis](https://www.npmjs.com/package/redis) client - this option overrides all previous\n\nUsing simple caching middleware\n=======================\n\nThis middleware simply caches response for given duration with `req.originalUrl` as caching key:\n\n    app.use('/pathPrefixToBeCachedForFiveSeconds', evc.cachingMiddleware(5000));\n\n\nUsing custom caching middleware\n=======================\n\nThis middleware accepts async function that extracts key name and ttl from request object.\nIt can be used for writing complicated caching rules, for example, these ones:\n\n\n```javascript\n\n// every path with /cacheCustom will be cached with key based on users IP  and ttl 3 seconds\napp.use('/cacheCustom', evc.customCachingMiddleware(function (req, cb) {\n  const key = `${req.ip}`;\n  return process.nextTick(function () {\n    cb(null, key, 3000);\n  });\n}));\n```\n\nConsider we have dashboard, that should be cached for 1 second for admin users, and for 5 seconds - to ordinary users.\nAnd every user has to have his/her own data.\n\n```javascript\n\nconst dashboardRouter = express.router();\n// consider we use PassportJS to reject unauthorized access\ndashboardRouter.use(function requireAuthorized(req, res, next) {\n  if(req.user) {\n    return next();\n  }\n  return  res.sendStatus(401);\n});\n\n// cache dashboard \ndashboardRouter.use('/dashboard', evc.customCachingMiddleware(function (req, cb) {\n  const key = `DashBoardForUser${req.user.id}`; // caching key contains useds ID\n  const ttl = req.user.admin ? 1000 : 5000; // caching TTL depends on users permissions\n  return process.nextTick(function () {\n    cb(null, key, ttl);\n  });\n}));\n\n// actually, generate personal dasboard for user\ndashboardRouter.get('/dashboard', function (req,res,next){\n  req.model.makeDashboardForUser(req.user, function (error, data){\n    if(error) {\n      return next(error);\n    }\n    return res.json(data);\n  });\n});\n\n\n```\n\n\n\n\nTests\n==================\n\n    $ npm run lint\n    $ npm test\n\nLicense\n====================\nThe MIT License (MIT)\n\nCopyright (c) 2013 Ostroumov Anatolij ostroumov095(at)gmail(dot)com et al.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvodolaz095%2Fexpress-view-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvodolaz095%2Fexpress-view-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvodolaz095%2Fexpress-view-cache/lists"}