Skip to content
This repository has been archived by the owner on Dec 30, 2022. It is now read-only.

fix(cache): cache handling #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
"prettier": "^1.17.0",
"@zeit/ncc": "^0.18.2",
"axios": "^0.19.0",
"node-cache": "^4.2.0"
"node-cache": "^5.0.1"
}
}
18 changes: 13 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ const cache = new NodeCache({ checkperiod: 240, deleteOnExpire: false })

const httpClient = axios.create({
baseURL: 'https://webtranslateit.com/api/projects',
timeout: 1000
timeout: 3000
})

const locked = new Set([])

const fetchProject = async token => {
let res
try {
Expand All @@ -26,7 +28,8 @@ const fetchProject = async token => {
res = project
cache.set(projectKey, project, PROJECT_CACHE_TTL)
} catch (e) {
console.log('Could not fetch WTI project')
console.log('Could not fetch WTI project', token)
console.log(e)
}

return res
Expand All @@ -51,7 +54,7 @@ const fetchTranslation = async (token, file) => {
}

const fetchData = async (token, locale) => {
let project = await cache.get(projectKey)
let project = cache.get(projectKey)
if (!project || !project.project_files) {
project = await fetchProject(token)
}
Expand Down Expand Up @@ -82,6 +85,10 @@ module.exports = ({
plainFunction = false
}) => {
cache.on('expired', async (key, value) => {
if (locked.has(key)) {
return
}
locked.add(key)
if (key === projectKey) {
await fetchProject(projectToken)
} else {
Expand All @@ -91,14 +98,15 @@ module.exports = ({
cache.set(key, data, ttl)
}
}
locked.delete(key)
})

if (plainFunction) {
return async locale => {
const key = `WTI::TRANSLATIONS::${locale}`

let data
const cachedVal = await cache.get(key)
const cachedVal = cache.get(key)

if (!cachedVal) {
data = await fetchData(projectToken, locale)
Expand All @@ -118,7 +126,7 @@ module.exports = ({
const key = `WTI::TRANSLATIONS::${locale}`

let data
const cachedVal = await cache.get(key)
const cachedVal = cache.get(key)

if (!cachedVal) {
data = await fetchData(projectToken, locale)
Expand Down