hierarchy.js 1.9 KB
Newer Older
1 2 3 4 5 6 7
import express from 'express';
import fs from 'fs';
import path from 'path';
import { NotFoundError } from '/common/error';

const router = express.Router();

8 9 10
const getPath = (...args) => path.resolve(__dirname, '..', 'public', 'algorithms', ...args);
const createKey = name => name.toLowerCase().replace(/ /g, '-');
const list = dirPath => fs.readdirSync(dirPath).filter(filename => !filename.startsWith('.'));
11

12
const cacheHierarchy = () => {
13 14 15 16 17 18 19 20 21 22 23 24 25
  const getCategory = categoryName => {
    const categoryKey = createKey(categoryName);
    const categoryPath = getPath(categoryName);
    const algorithms = list(categoryPath).map(algorithmName => getAlgorithm(categoryName, algorithmName));
    return {
      key: categoryKey,
      name: categoryName,
      algorithms,
    };
  };
  const getAlgorithm = (categoryName, algorithmName) => {
    const algorithmKey = createKey(algorithmName);
    const algorithmPath = getPath(categoryName, algorithmName);
J
Jason Park 已提交
26
    const files = list(algorithmPath);
27 28 29 30
    return {
      key: algorithmKey,
      name: algorithmName,
      files,
31
    };
32 33 34 35
  };
  return list(getPath()).map(getCategory);
};

36
const hierarchy = cacheHierarchy();
37

38 39
const getHierarchy = (req, res, next) => {
  res.json({ hierarchy });
40 41 42
};

const getFile = (req, res, next) => {
J
Jason Park 已提交
43
  const { categoryKey, algorithmKey, fileName } = req.params;
44

45
  const category = hierarchy.find(category => category.key === categoryKey);
46 47 48
  if (!category) return next(new NotFoundError());
  const algorithm = category.algorithms.find(algorithm => algorithm.key === algorithmKey);
  if (!algorithm) return next(new NotFoundError());
J
Jason Park 已提交
49
  if (!algorithm.files.includes(fileName)) return next(new NotFoundError());
50

J
Jason Park 已提交
51 52
  const filePath = getPath(category.name, algorithm.name, fileName);
  res.sendFile(filePath);
53 54 55
};

router.route('/')
56
  .get(getHierarchy);
57

J
Jason Park 已提交
58
router.route('/:categoryKey/:algorithmKey/:fileName')
59 60 61
  .get(getFile);

export default router;