aboutsummaryrefslogtreecommitdiff
path: root/src/lib/nginxAdapter.ts
blob: fdadd8707a9af11b2b43b9829a54ffc6c2693e1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import _ from 'lodash';
import Bluebird from 'bluebird';
import axios from 'axios';
import mem from 'mem';
import { Adapter } from './types';

const listNginxDirectory = async (path: string): Promise<string[]> => {
  const basePath = _.trimEnd(path.match('http[s]?://(.*?)/')?.[0], '/');
  const response = await axios(path);
  const [_thisDir, ...results] = response.data
    .match(/href='(.*)'/g)
    .map((s: string) => s.match(/'(.*)'/)?.[1])
    .map((s: string) => basePath + s);
  return results;
}

const deepListNginxDirectory = async (path: string): Promise<string[]> => {
  const objects = await listNginxDirectory(path);
  const fileUrls = objects.filter(url => !url.endsWith('/'));
  const dirUrls = objects.filter(url => url.endsWith('/'));
  const deepFileUrls = await Bluebird.map(dirUrls, deepListNginxDirectory);
  return _.flattenDeep([fileUrls, deepFileUrls]);
}

const memoizedDeepListNginxDirectory = mem(deepListNginxDirectory, { maxAge: 60000 });


// An adapter to fetch markdown & images from Nginx server with enabled directory view
const nginxAdapter: Adapter = {
  async getStaticMarkdownPaths(cdn) {
    const urls = await memoizedDeepListNginxDirectory(cdn);
    const markdownPaths = _.compact(urls.map(globalPath => globalPath.match(`${cdn}/(.*)\.md`)?.[1]));

    return markdownPaths
      .map(path => path.split('/'))
      .map(path => ({ params: { path } }));
  },

  async getMarkdownSource(cdn, path) {
    const { data: markdownSource } = await axios(`${cdn}/${path?.join('/')}.md`);
    return markdownSource;
  },

  async getEmojiFileNames(cdn) {
    const urls = await memoizedDeepListNginxDirectory(cdn);
    return _.compact(urls.map((s: string) => s.match(/emoji\/(.*)/)?.[1]));
  },
}

export default nginxAdapter;