import { IApiTokenStore } from '../../lib/types/stores/api-token-store'; import { IApiToken, IApiTokenCreate } from '../../lib/types/models/api-token'; import NotFoundError from '../../lib/error/notfound-error'; import EventEmitter from 'events'; export default class FakeApiTokenStore extends EventEmitter implements IApiTokenStore { tokens: IApiToken[] = []; async delete(key: string): Promise { this.tokens.splice( this.tokens.findIndex((t) => t.secret === key), 1, ); } async count(): Promise { return this.tokens.length; } async deleteAll(): Promise { this.tokens = []; } destroy(): void {} async exists(key: string): Promise { return this.tokens.some((token) => token.secret === key); } async get(key: string): Promise { const token = this.tokens.find((t) => t.secret === key); if (token) { return token; } throw new NotFoundError(`Could not find token with secret ${key}`); } async getAll(): Promise { return this.tokens; } async getAllActive(): Promise { return this.tokens.filter((token) => token.expiresAt > new Date()); } async insert(newToken: IApiTokenCreate): Promise { const apiToken = { createdAt: new Date(), project: newToken.projects?.join(',') || '*', ...newToken, metadata: {}, }; this.tokens.push(apiToken); this.emit('insert'); return apiToken; } async markSeenAt(secrets: string[]): Promise { this.tokens .filter((t) => secrets.includes(t.secret)) .forEach((t) => { // eslint-disable-next-line no-param-reassign t.seenAt = new Date(); }); } async setExpiry(secret: string, expiresAt: Date): Promise { const t = await this.get(secret); t.expiresAt = expiresAt; return t; } }