How to use apicache - 10 common examples

To help you get started, we’ve selected a few apicache examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zackexplosion / YT-stream-keyword-counter / web / chartdata-total-months.js View on Github external
const KEYWORDS = (process.env.TARGET_KEYWORDS || '韓|國瑜|韓國瑜').split('|')
const CHARTDATA_CACHE_SECONDS = process.env.chartdata_CACHE_SECONDS || 60 * 60
const path = require('path')
const CHANNELS = require(path.join(ROOT_DIR, 'util', 'channels'))
const cache_middleware = require('apicache').middleware(`${CHARTDATA_CACHE_SECONDS} seconds`)

function countchartdata(channel) {
  // this time is multi scanner deploy time
  const startTime = moment('2019-04-07T13:27:12.791Z')
  let matches = db.get(channel.id).value().filter(m => {
    // filter by record time
    let a = moment(m[0])

    const startOfMonth = moment().startOf('month')
    const endOfMonth   = moment().endOf('month')

    // make sure it's in this month and new than starTime
    return (
      a >= startTime &&
      a >= startOfMonth &&
      a <= endOfMonth
github Binaryify / NeteaseCloudMusicApi / app.js View on Github external
// cookie parser
app.use((req, res, next) => {
  req.cookies = {}, (req.headers.cookie || '').split(/\s*;\s*/).forEach(pair => {
    let crack = pair.indexOf('=')
    if(crack < 1 || crack == pair.length - 1) return
    req.cookies[decodeURIComponent(pair.slice(0, crack)).trim()] = decodeURIComponent(pair.slice(crack + 1)).trim()
  })
  next()
})

// body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

// cache
app.use(cache('2 minutes', ((req, res) => res.statusCode === 200)))

// static
app.use(express.static(path.join(__dirname, 'public')))

// router
const special = {
  'daily_signin.js': '/daily_signin',
  'fm_trash.js': '/fm_trash',
  'personal_fm.js': '/personal_fm'
}

fs.readdirSync(path.join(__dirname, 'module')).reverse().forEach(file => {
  if(!file.endsWith('.js')) return
  let route = (file in special) ? special[file] : '/' + file.replace(/\.js$/i, '').replace(/_/g, '/')
  let question = require(path.join(__dirname, 'module', file))
github Pupix / lol-riot-api / app.js View on Github external
}
    } else {
      require('dotenv').load();
      app.use(cors()); // use CORS
      app.use(helmet()); // Secure the API with helmet. Readmore: https://expressjs.com/en/advanced/best-practice-security.html
      app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc)
      // Ratelimiter
      var limiter = new RateLimit({
        windowMs: 10 * 60 * 1000, // 10 minutes
        max: 1000, // limit each IP to 100 requests per windowMs
        delayMs: 0 // disable delaying - full speed until the max limit is reached
      });
      app.use(limiter);

      // Set Cache Options
      apicache.options({
          redisClient: redis.createClient()
      }, {
          statusCodes: {
              exclude: [404, 429, 500],
              include: [200, 304]
          }
      }).middleware;

      api = new API({
        key: process.env.KEY || null,
        region: process.env.REGION || null
      });

      app.port = process.env.PORT || 3001;

      // Default route
github nuxt-community / hackernews-nuxt-ts / common / cache.ts View on Github external
import express from "express"
import apicache from "apicache"

const app = express()

// https://github.com/kwhitley/apicache
app.use(apicache.middleware("15 minutes"))

// apicache.options({ debug: true })

export default {
  path: "/api/",
  handler: app
}
github sensebox / openSenseMap-API / packages / api / lib / helpers / apiUtils.js View on Github external
const addCache = function addCache (duration, group) {
  // configure the apicache, set the group and only cache response code 200 responses
  const apicacheMiddlewareFunction = function apicacheMiddlewareFunction (req, res) {
    req.apicacheGroup = group;

    return res.statusCode === 200;
  };

  return apicache.middleware(duration, apicacheMiddlewareFunction);
};
github aluxian / squirrel-updates-server / src / server.js View on Github external
ravenClient = new raven.Client(config.sentry.dsn, {
    release: manifest.version
  });
  global.ravenClient = ravenClient;
}

app.use(morgan('common'));
if (ravenClient) {
  app.use(raven.middleware.express.requestHandler(ravenClient));
}

// apicache does not cache headers on redirects, so do not cache if configured appropriately
if (config.cacheIgnoreRedirects) {
    let cacheOptions = apicache.options();
    cacheOptions.statusCodes.exclude = [301, 302];
    apicache.options(cacheOptions);
}
const cache = () => {
  return apicache.middleware(config.cacheTTL);
};

app.get('/', cache(), asyncHandler(homeCtrl.main));
app.get('/update/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/update/:channel/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/:channel/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/:channel/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/:channel/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/download/mirror/:mirror/latest', asyncHandler(downloadCtrl.latestMirror));
app.get('/download/:platform/latest', cache(), asyncHandler(downloadCtrl.latest));
github aluxian / squirrel-updates-server / src / server.js View on Github external
if (config.sentry && config.sentry.dsn) {
  ravenClient = new raven.Client(config.sentry.dsn, {
    release: manifest.version
  });
  global.ravenClient = ravenClient;
}

app.use(morgan('common'));
if (ravenClient) {
  app.use(raven.middleware.express.requestHandler(ravenClient));
}

// apicache does not cache headers on redirects, so do not cache if configured appropriately
if (config.cacheIgnoreRedirects) {
    let cacheOptions = apicache.options();
    cacheOptions.statusCodes.exclude = [301, 302];
    apicache.options(cacheOptions);
}
const cache = () => {
  return apicache.middleware(config.cacheTTL);
};

app.get('/', cache(), asyncHandler(homeCtrl.main));
app.get('/update/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/update/:channel/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/:channel/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/:channel/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/:channel/linux', cache(), asyncHandler(updateCtrl.linux));
github quran / quran.com-frontend / server / routes.js View on Github external
import superagent from 'superagent';
import * as Settings from 'constants/Settings';
// Cache for the time being until we change this
const apicache = require('apicache')
const cache = apicache.options({ debug: true }).middleware;

import debugLib from 'debug';
const debug = debugLib('quran');

export default function(server) {
  server.get('/api/cache/index', function(req, res, next) {
    return res.status(200).send(apicache.getIndex());
  });
  server.get('/api/cache/clear', function(req, res, next) {
    return res.send(200, apicache.clear());
  });

  server.get(/^\/(images|fonts)\/.*/, function(req, res) {
    res.redirect(301, '//quran-1f14.kxcdn.com' + req.path);
  });
github wazuh / wazuh-api / controllers / index.js View on Github external
var router = require('express').Router();
var os = require("os");

// Cache options
if (config.cache_enabled.toLowerCase() == "yes"){
    if (config.cache_debug.toLowerCase() == "yes")
        cache_debug = true;
    else
        cache_debug = false;
    cache_opt = { debug: cache_debug, defaultDuration: parseInt(config.cache_time)};
}
else
    cache_opt = { enabled: false };

apicache.options(cache_opt);

// Content-type
router.post("*", function(req, res, next) {
    var content_type = req.get('Content-Type');

    if (!content_type || !(content_type == 'application/json' || content_type == 'application/x-www-form-urlencoded'
        || content_type == 'application/xml' || content_type == 'application/octet-stream')){
        logger.debug(req.connection.remoteAddress + " POST " + req.path);
        res_h.bad_request(req, res, "607");
    }
    else
        next();
});

// All requests
router.all("*", function(req, res, next) {
github pokelondon / pintsinthesun / src / server / main.js View on Github external
/*
 * Data persistence service
 * WSP Ltd. 2016
 */

// Libs
// ================================================================
var express = require('express');

var MongoClient = require('mongodb').MongoClient;
var http = require('http');
var assert = require('assert');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var apicache = require('apicache').options({ debug: true });
var apimiddleware = apicache.middleware;

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');

var PubModel = require('./models/pub');
var UserModel = require('./models/user');

require('es6-promise').polyfill();
require('isomorphic-fetch');

var SunCalc = require('../app/lib/suncalc')

var config = require('./config');

apicache

An ultra-simplified API response caching middleware for Express/Node using plain-english durations.

MIT
Latest version published 3 years ago

Package Health Score

59 / 100
Full package analysis