How to use the apicache.middleware function in apicache

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 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 mlaursen / react-md / api / src / server / index.js View on Github external
app.use(compression());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(logger(__DEV__ ? 'dev' : 'combined'));

if (__DEV__ && path) {
  const router = express.Router();
  router.use('/docgens', cache(CACHE_DURATION), docgen);
  router.use('/sassdocs', cache(CACHE_DURATION), sassdoc);
  router.use('/search', cache(CACHE_DURATION), search);

  app.use(path, router);
} else {
  app.use('/docgens', cache(CACHE_DURATION), docgen);
  app.use('/sassdocs', cache(CACHE_DURATION), sassdoc);
  app.use('/search', cache(CACHE_DURATION), search);
}

(async () => {
  await Promise.all([buildDocgenDB(), buildSassDocDB(), buildSearchDB()]);

  app.listen(port, err => {
    if (err) {
      throw err;
    }

    console.log(`Listening to api calls on port ${port}`);
  });
})();
github PokemonGoers / PokeData / routes.js View on Github external
router.get('/pokemon/id/:id/icon/svg', cache('60 minutes'), pokemon.getSvgIconById);

    //route for getting pokemon details by specific gender
    router.get('/pokemon/gender/:gender', cache('60 minutes'), pokemon.getByGender);

    //route for getting pokemon details by specific name
    router.get('/pokemon/name/:name', cache('60 minutes'), pokemon.getByName);

    //route for getting pokemon details by description
    router.get('/pokemon/description/:description', cache('60 minutes'), pokemon.getByDescription);

    //route for getting pokemon details by specific type
    router.get('/pokemon/type/:type', cache('60 minutes'), pokemon.getByType);

    //route for getting pokemon details by specific resistance
    router.get('/pokemon/resistance/:resistance', cache('60 minutes'), pokemon.getByResistance);

    //route for getting pokemon details by specific weakness
    router.get('/pokemon/weakness/:weakness', cache('60 minutes'), pokemon.getByWeakness);

    //route for getting pokemon details by specific weakness
    router.get('/pokemon/attack/:category(fast|special)/type/:type', cache('60 minutes'), pokemon.getByAttackType);

    //route for getting pokemon details by specific weakness
    router.get('/pokemon/attack/:category(fast|special)/name/:name', cache('60 minutes'), pokemon.getByAttackName);

    //route for getting pokemon details by specific weakness
    router.get('/pokemon/attack/:category(fast|special)/damage/:damage', cache('60 minutes'), pokemon.getByAttackDamage);

    //route for getting pokemon details by specific weakness
    router.get('/pokemon/evolution/:category(prev|next)/id/:id', cache('60 minutes'), pokemon.getByEvolutionId);
github dana-ross / adrian / app / src / server.js View on Github external
/**
 * Routes to serve fonts
 */
(function () {
    ['otf', 'ttf', 'woff', 'woff2'].forEach((extension) => {
        app.get(`/font/:id\.${extension}`, (req, res) => {
            fs.createReadStream(findFontByID(fonts, req.params.id).filename).pipe(res)
        })
    })
}())

/**
 * Route to serve CSS
 */
app.get('/font/:name\.css', apicache.middleware(cacheLifetime), (req, res)=> {
    if(findFontByName(fonts, req.params.name)) {
        res.write(fontFaceCSS(findFontByName(fonts, req.params.name), req.protocol))
    }
    else {
        res.statusCode = 404
    }
    res.end()
})

app.get('/font/family/:name.css', apicache.middleware(cacheLifetime), (req, res) => {
    const familyMembers = findFontsByFamilyName(fonts, req.params.name)
    if(familyMembers.length) {
        familyMembers.forEach((font) => res.write(fontFaceCSS(font)) + "\n")
    }
    else {
        res.statusCode = 404
github mlaursen / react-md / documentation / src / server / api / index.js View on Github external
import github from './github';
import airQuality from './airQuality';
import fakeUpload from './fakeUpload';
import {
  DOCGENS_ENDPOINT,
  SASSDOCS_ENDPOINT,
  SEARCH_ENDPOINT,
  GITHUB_ENDPOINT,
  AIR_QUALITY_ENDPOINT,
  FAKE_UPLOAD_ENDPOINT,
} from 'constants/application';

const CACHE_DURATION = '10 days';
const apiRouter = express.Router();

apiRouter.use(cache(CACHE_DURATION));
apiRouter.use(bodyParser.urlencoded({ extended: true }));
apiRouter.use(FAKE_UPLOAD_ENDPOINT, fakeUpload);

apiRouter.use(bodyParser.json());

apiRouter.use(DOCGENS_ENDPOINT, docgens);
apiRouter.use(SASSDOCS_ENDPOINT, sassdocs);
apiRouter.use(SEARCH_ENDPOINT, search);
apiRouter.use(GITHUB_ENDPOINT, github);
apiRouter.use(AIR_QUALITY_ENDPOINT, airQuality);
apiRouter.get('*', (req, res) => {
  res.sendStatus(NOT_FOUND);
});

export default apiRouter;
github aluxian / squirrel-updates-server / src / server.js View on Github external
const cache = () => {
  return apicache.middleware(config.cacheTTL);
};

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