Skip to content

Commit

Permalink
Merge pull request #6 from vercel-labs/cache
Browse files Browse the repository at this point in the history
feat: add cache
  • Loading branch information
Kikobeats authored Dec 12, 2024
2 parents 21bd807 + e59da60 commit 2041116
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
],
"dependencies": {
"arg": "~5.0.2",
"find-cache-dir": "~5.0.0",
"mri": "~1.2.0",
"open": "~10.1.0",
"picocolors": "~1.1.1",
Expand Down
29 changes: 29 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { mkdir, writeFile, readFile } from 'fs/promises'
import findCacheDirectory from 'find-cache-dir'
import { existsSync } from 'fs'
import path from 'path'

export const createCache = () => {
const cacheDir = findCacheDirectory({ name: 'vercel-open' })
const cachePath = path.resolve(cacheDir!, 'cache.json')

const cacheFilePromise = (async () => {
try {
return JSON.parse(await readFile(cachePath, 'utf-8'))
} catch (error) {
return {}
}
})()

return {
read: () => cacheFilePromise,
write: async (data: any) => {
const cache = await cacheFilePromise
const newData = { ...cache, ...data }
if (!existsSync(cacheDir!)) {
await mkdir(cacheDir!, { recursive: true })
}
await writeFile(cachePath, JSON.stringify(newData, null, 2), 'utf-8')
}
}
}
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { readFile } from 'fs/promises'
import { existsSync } from 'fs'
import path from 'path'

import { createCache } from './cache.js'

const cache = createCache()

const vercelApi = (pathname: string) =>
fetch(`${process.env.VERCEL_API}/${pathname}`, {
headers: {
Expand Down Expand Up @@ -51,9 +55,15 @@ async function readProjectFile (): Promise<{
}

async function fromPath (): Promise<{ org: string; project: string }> {
const cached = await cache.read()
if (cached.org && cached.project) return cached

const { projectId, teamId } = await readProjectFile()
const org = await getOrganizationName(teamId)
const project = await getProjectName(projectId, teamId)

await cache.write({ org, project })

return { org, project }
}

Expand Down

0 comments on commit 2041116

Please sign in to comment.