All files / src/lib/routes/client-api register.ts

78.95% Statements 15/19
0% Branches 0/6
100% Functions 3/3
78.95% Lines 15/19

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  59x             59x 59x 59x   59x                     141x 141x 141x     141x       9x             9x       9x 9x 9x 7x      
import { Response } from 'express';
import Controller from '../controller';
import { IUnleashServices } from '../../types';
import { IUnleashConfig } from '../../types/option';
import { Logger } from '../../logger';
import ClientInstanceService from '../../services/client-metrics/instance-service';
import { IAuthRequest, User } from '../../server-impl';
import { IClientApp } from '../../types/model';
import ApiUser from '../../types/api-user';
import { ALL } from '../../types/models/api-token';
import { NONE } from '../../types/permissions';
 
export default class RegisterController extends Controller {
    logger: Logger;
 
    metrics: ClientInstanceService;
 
    constructor(
        {
            clientInstanceService,
        }: Pick<IUnleashServices, 'clientInstanceService'>,
        config: IUnleashConfig,
    ) {
        super(config);
        this.logger = config.getLogger('/api/client/register');
        this.metrics = clientInstanceService;
 
        // NONE permission is not optimal here in terms of readability.
        this.post('/', this.handleRegister, NONE);
    }
 
    private resolveEnvironment(user: User, data: IClientApp) {
        Iif (user instanceof ApiUser) {
            if (user.environment !== ALL) {
                return user.environment;
            } else Iif (user.environment === ALL && data.environment) {
                return data.environment;
            }
        }
        return 'default';
    }
 
    async handleRegister(req: IAuthRequest, res: Response): Promise<void> {
        const { body: data, ip: clientIp, user } = req;
        data.environment = this.resolveEnvironment(user, data);
        await this.metrics.registerClient(data, clientIp);
        return res.status(202).end();
    }
}