refactor: Add isCachedToken type guard for improved cache validation and remove await from cache file operations.
This commit is contained in:
parent
9e63027e47
commit
f5e340b46c
@ -27,14 +27,31 @@ export function deriveCopilotApiBaseUrlFromToken(token: string): string {
|
|||||||
|
|
||||||
type ResolveOptions = { githubToken: string; fetchImpl: typeof fetch };
|
type ResolveOptions = { githubToken: string; fetchImpl: typeof fetch };
|
||||||
|
|
||||||
|
interface CachedToken {
|
||||||
|
token: string;
|
||||||
|
expiresAt: number;
|
||||||
|
updatedAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCachedToken(value: unknown): value is CachedToken {
|
||||||
|
return (
|
||||||
|
typeof value === "object" &&
|
||||||
|
value !== null &&
|
||||||
|
"token" in value &&
|
||||||
|
typeof (value as CachedToken).token === "string" &&
|
||||||
|
"expiresAt" in value &&
|
||||||
|
typeof (value as CachedToken).expiresAt === "number"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function resolveCopilotApiToken(opts: ResolveOptions) {
|
export async function resolveCopilotApiToken(opts: ResolveOptions) {
|
||||||
const stateDir = resolveStateDir();
|
const stateDir = resolveStateDir();
|
||||||
const cachePath = path.join(stateDir, "github-copilot-token.json");
|
const cachePath = path.join(stateDir, "github-copilot-token.json");
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const cached = await loadJsonFile(cachePath);
|
const cached = loadJsonFile(cachePath);
|
||||||
if (cached && typeof cached.expiresAt === "number" && cached.expiresAt > now) {
|
if (isCachedToken(cached) && cached.expiresAt > now) {
|
||||||
return {
|
return {
|
||||||
token: cached.token,
|
token: cached.token,
|
||||||
baseUrl: deriveCopilotApiBaseUrlFromToken(cached.token),
|
baseUrl: deriveCopilotApiBaseUrlFromToken(cached.token),
|
||||||
@ -60,7 +77,7 @@ export async function resolveCopilotApiToken(opts: ResolveOptions) {
|
|||||||
const expiresAt = expires_at * 1000;
|
const expiresAt = expires_at * 1000;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await saveJsonFile(cachePath, { token, expiresAt, updatedAt: Date.now() });
|
saveJsonFile(cachePath, { token, expiresAt, updatedAt: Date.now() });
|
||||||
} catch {
|
} catch {
|
||||||
// ignore save errors
|
// ignore save errors
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user