All files / src/lib/services tag-service.ts

100% Statements 22/22
100% Branches 1/1
100% Functions 8/8
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 7660x 60x 60x               60x                           147x 147x 147x       4x       2x       4x       3x 3x 1x         4x 3x 2x       4x 2x 2x               2x 2x               60x  
import { tagSchema } from './tag-schema';
import NameExistsError from '../error/name-exists-error';
import { TAG_CREATED, TAG_DELETED } from '../types/events';
import { Logger } from '../logger';
import { IUnleashStores } from '../types/stores';
import { IUnleashConfig } from '../types/option';
import { ITagStore } from '../types/stores/tag-store';
import { IEventStore } from '../types/stores/event-store';
import { ITag } from '../types/model';
 
export default class TagService {
    private tagStore: ITagStore;
 
    private eventStore: IEventStore;
 
    private logger: Logger;
 
    constructor(
        {
            tagStore,
            eventStore,
        }: Pick<IUnleashStores, 'tagStore' | 'eventStore'>,
        { getLogger }: Pick<IUnleashConfig, 'getLogger'>,
    ) {
        this.tagStore = tagStore;
        this.eventStore = eventStore;
        this.logger = getLogger('services/tag-service.js');
    }
 
    async getTags(): Promise<ITag[]> {
        return this.tagStore.getAll();
    }
 
    async getTagsByType(type: string): Promise<ITag[]> {
        return this.tagStore.getTagsByType(type);
    }
 
    async getTag({ type, value }: ITag): Promise<ITag> {
        return this.tagStore.getTag(type, value);
    }
 
    async validateUnique(tag: ITag): Promise<void> {
        const exists = await this.tagStore.exists(tag);
        if (exists) {
            throw new NameExistsError(`A tag of ${tag} already exists`);
        }
    }
 
    async validate(tag: ITag): Promise<ITag> {
        const data = (await tagSchema.validateAsync(tag)) as ITag;
        await this.validateUnique(tag);
        return data;
    }
 
    async createTag(tag: ITag, userName: string): Promise<void> {
        const data = await this.validate(tag);
        await this.tagStore.createTag(data);
        await this.eventStore.store({
            type: TAG_CREATED,
            createdBy: userName,
            data,
        });
    }
 
    async deleteTag(tag: ITag, userName: string): Promise<void> {
        await this.tagStore.delete(tag);
        await this.eventStore.store({
            type: TAG_DELETED,
            createdBy: userName,
            data: tag,
        });
    }
}
 
module.exports = TagService;