All files / src/operation update-node.ts

100% Statements 26/26
100% Branches 2/2
100% Functions 5/5
100% Lines 26/26

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 76 77 78 79 80 81 82    2x   2x 2x                                 5x   5x     5x 16x   16x   16x     5x 1x     4x       16x 16x 16x 16x   16x               16x   16x       5x   5x       16x   16x       16x   16x       2x  
import Node from 'type/node';
import ChangeType from 'enum/change-type';
import BadRequestError from 'http/error/bad-request';
import { PrimitiveValue } from 'type/field-value';
import ChangeFieldOperation from 'operation/change-field';
import Operation, { OperationInput } from 'operation';
 
export interface ChangeInput {
	readonly change_type: ChangeType;
	readonly field: string;
	readonly value: PrimitiveValue;
	readonly previous_value: PrimitiveValue | null;
}
 
export interface Input extends OperationInput {
	readonly id: string;
	readonly type_id: string;
	readonly changes: ChangeInput[];
}
 
class UpdateNodeOperation extends Operation<Input, Node> {
	protected async performInternal(): Promise<Node> {
		const changes = this.getChanges();
 
		let index = 0;
		let node: Node | undefined;
 
		while (index < changes.length) {
			const change = changes[index];
 
			node = await this.applyChange(change);
 
			index++;
		}
 
		if (node === undefined) {
			throw new BadRequestError();
		}
 
		return node;
	}
 
	private applyChange(change: ChangeInput): Promise<Node> {
		const id = this.getNodeId();
		const type_id = this.getTypeId();
		const repository = this.getRepository();
		const account = this.getAccount();
 
		const input = {
			id,
			type_id,
			...change,
			repository,
			account
		};
 
		const service = new ChangeFieldOperation(input);
 
		return service.perform();
	}
 
	private getChanges(): ChangeInput[] {
		const input = this.getInput();
 
		return input.changes;
	}
 
	private getTypeId(): string {
		const input = this.getInput();
 
		return input.type_id;
	}
 
	private getNodeId(): string {
		const input = this.getInput();
 
		return input.id;
	}
}
 
export default UpdateNodeOperation;