-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Cache GitLab responses to avoid spamming the GitLab server
- Loading branch information
Showing
2 changed files
with
84 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright 2018 Roger Meier <[email protected]> | ||
// SPDX-License-Identifier: MIT | ||
|
||
import Crypto from 'crypto'; | ||
|
||
import {Logger} from '@verdaccio/types'; | ||
import NodeCache from 'node-cache'; | ||
|
||
export class GitlabCache { | ||
private logger: Logger; | ||
private ttl: number; | ||
private storage: NodeCache; | ||
|
||
public static get DEFAULT_TTL() { | ||
return 300; | ||
} | ||
|
||
private static _generateKeyHash(username: string, password: string) { | ||
const sha = Crypto.createHash('sha256'); | ||
sha.update(JSON.stringify({ username: username, password: password })); | ||
return sha.digest('hex'); | ||
} | ||
|
||
public constructor(logger: Logger, ttl?: number) { | ||
this.logger = logger; | ||
this.ttl = ttl || GitlabCache.DEFAULT_TTL; | ||
|
||
this.storage = new NodeCache({ | ||
stdTTL: this.ttl, | ||
useClones: false, | ||
}); | ||
this.storage.on('expired', (key, value) => { | ||
this.logger.trace(`[gitlab] expired key: ${key} with value:`, value); | ||
}); | ||
} | ||
|
||
public getPromise(username: string, password: string, type: 'user' | 'groups' | 'projects'): Promise<any> { | ||
return this.storage.get(GitlabCache._generateKeyHash(`${username}_${type}_promise`, password)) as Promise<any>; | ||
} | ||
|
||
public storePromise(username: string, password: string, type: 'user' | 'groups' | 'projects', promise: Promise<any>): boolean { | ||
return this.storage.set(GitlabCache._generateKeyHash(`${username}_${type}_promise`, password), promise); | ||
} | ||
} |