From 5b15fb45cfc06b52a61bd4611fb9f278094a01b0 Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Tue, 2 Jan 2024 11:29:42 +0100 Subject: [PATCH] perf: cache env utils --- packages/core/package.json | 1 + packages/core/src/util/env.ts | 21 +++++++++++++++++++++ pnpm-lock.yaml | 3 +++ 3 files changed, 25 insertions(+) diff --git a/packages/core/package.json b/packages/core/package.json index aec99b9..05d1ae6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -53,6 +53,7 @@ "get-port-please": "^3.1.1", "graphql-yoga": "^5.0.2", "jiti": "^1.21.0", + "lru-cache": "^10.1.0", "nanoid": "^5.0.4", "pathe": "^1.1.1", "perfect-debounce": "^1.0.0", diff --git a/packages/core/src/util/env.ts b/packages/core/src/util/env.ts index 21b4763..ecbe512 100644 --- a/packages/core/src/util/env.ts +++ b/packages/core/src/util/env.ts @@ -1,18 +1,29 @@ import process from 'node:process' import fs from 'node:fs' import path from 'pathe' +import { LRUCache } from 'lru-cache' import { findUp } from './find-up.js' export function getCwd() { return path.resolve(process.env.MOQUERIE_OVERRIDE_CWD ?? process.cwd()) } +const projectNameCache = new LRUCache({ + max: 100, + ttl: 5000, +}) + export function getProjectName(): string { const cwd = getCwd() + const cached = projectNameCache.get(cwd) + if (cached) { + return cached + } const pkgFile = findUp(cwd, ['package.json']) if (pkgFile) { try { const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8')) + projectNameCache.set(cwd, pkg.name) return pkg.name } catch (e: any) { @@ -22,8 +33,18 @@ export function getProjectName(): string { throw new Error(`[moquerie] package.json not found looking from ${cwd}`) } +const projectHasTypescriptCache = new LRUCache({ + max: 100, + ttl: 1000 * 60 * 5, +}) + export function projectHasTypescript(): boolean { const cwd = getCwd() + const cached = projectHasTypescriptCache.get(cwd) + if (cached !== undefined) { + return cached + } const tsconfigFile = findUp(cwd, ['tsconfig.json']) + projectHasTypescriptCache.set(cwd, !!tsconfigFile) return !!tsconfigFile } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3bea0a3..f7f45f2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -146,6 +146,9 @@ importers: jiti: specifier: ^1.21.0 version: 1.21.0 + lru-cache: + specifier: ^10.1.0 + version: 10.1.0 nanoid: specifier: ^5.0.4 version: 5.0.4