All files / packages/value/src optional.ts

92.3% Statements 12/13
76.92% Branches 10/13
100% Functions 5/5
92.3% Lines 12/13

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                            964x 964x           1857x       157x 157x     157x                   960x           960x 960x       416x 416x           416x      
import { type MessageInitShape, create } from '@bufbuild/protobuf'
import type { GenMessage } from '@bufbuild/protobuf/codegenv1'
import * as Ydb from '@ydbjs/api/value'
 
import { Null } from './null.js'
import { type Type, TypeKind } from './type.js'
import type { Value } from './value.js'
 
export class OptionalType implements Type {
	readonly itemType: Type
	#type: MessageInitShape<GenMessage<Ydb.Type>>
	#typeInstance?: Ydb.Type
 
	constructor(itemType: Type) {
		this.itemType = itemType
		this.#type = {
			type: { case: 'optionalType', value: { item: itemType.encode() } },
		}
	}
 
	get kind(): TypeKind.OPTIONAL {
		return TypeKind.OPTIONAL
	}
 
	encode(): Ydb.Type {
		Eif (!this.#typeInstance) {
			this.#typeInstance = create(Ydb.TypeSchema, this.#type)
		}
 
		return this.#typeInstance
	}
}
 
export class Optional<T extends Type> implements Value<OptionalType> {
	readonly type: OptionalType
	readonly item: Value<T> | null
	#valueInstance?: Ydb.Value
 
	constructor(item: Value<T> | null, itemType?: T) {
		Iif ((!itemType || itemType instanceof Null) && !item?.type) {
			throw new Error(
				'Missing item type for optional value. Please provide an item type. Or provide an item with a type.'
			)
		}
 
		this.item = item
		this.type = new OptionalType((item?.type || itemType) as Type)
	}
 
	encode(): Ydb.Value {
		Eif (!this.#valueInstance) {
			this.#valueInstance = create(
				Ydb.ValueSchema,
				this.item === null ? new Null().encode() : this.item.encode()
			)
		}
 
		return this.#valueInstance
	}
}