Skip to content

Commit

Permalink
feat: cache certificate (#3642)
Browse files Browse the repository at this point in the history
Co-authored-by: Shinigami <chrissi92@hotmail.de>
  • Loading branch information
wmzy and Shinigami92 committed Jul 7, 2021
1 parent 98d95e3 commit 5dd670f
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions packages/vite/src/node/server/http.ts
@@ -1,4 +1,4 @@
import fs from 'fs'
import fs, { promises as fsp } from 'fs'
import path from 'path'
import { Server as HttpServer } from 'http'
import { ServerOptions as HttpsServerOptions } from 'https'
Expand Down Expand Up @@ -44,7 +44,7 @@ export async function resolveHttpsConfig(
pfx: readFileIfExists(pfx)
})
if (!httpsOption.key || !httpsOption.cert) {
httpsOption.cert = httpsOption.key = await createCertificate()
httpsOption.cert = httpsOption.key = await getCertificate(config)
}
return httpsOption
}
Expand Down Expand Up @@ -133,3 +133,29 @@ async function createCertificate() {
})
return pems.private + pems.cert
}

async function getCertificate(config: ResolvedConfig) {
if (!config.cacheDir) return await createCertificate()

const cachePath = path.join(config.cacheDir, '_cert.pem')

try {
const [stat, content] = await Promise.all([
fsp.stat(cachePath),
fsp.readFile(cachePath, 'utf8')
])

if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
throw new Error('cache is outdated.')
}

return content
} catch {
const content = await createCertificate()
fsp
.mkdir(config.cacheDir, { recursive: true })
.then(() => fsp.writeFile(cachePath, content))
.catch(() => {})
return content
}
}

0 comments on commit 5dd670f

Please sign in to comment.