File size: 1,072 Bytes
cdc50ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import { normalizeTitle } from '../utils/normalize.js';

const __dirname = path.dirname( fileURLToPath( import.meta.url ) );
const CACHE_DIR = path.join( __dirname, '..', 'cache' );

export async function getCached( title ) {
	const filename = `${ normalizeTitle( title ) }.json`;
	const filepath = path.join( CACHE_DIR, filename );

	try {
		const data = await fs.readFile( filepath, 'utf-8' );
		return JSON.parse( data );
	} catch ( e ) {
		if ( e.code === 'ENOENT' ) {
			return null;
		}
		throw e;
	}
}

export async function setCache( title, data ) {
	await fs.mkdir( CACHE_DIR, { recursive: true } );
	const filename = `${ normalizeTitle( title ) }.json`;
	const filepath = path.join( CACHE_DIR, filename );
	await fs.writeFile( filepath, JSON.stringify( data, null, 2 ) );
}

export async function isCacheValid( title, currentRevisionId ) {
	const cached = await getCached( title );
	if ( !cached ) {
		return false;
	}
	return cached.revisionId === currentRevisionId;
}