@getgreenspark/widgets
Version:
An SDK design to help the use of Greenspark's widget API in the browser
59 lines (50 loc) • 1.83 kB
text/typescript
import type { WidgetConfig } from '@/widgets/base'
import { Widget } from '@/widgets/base'
import type { PerProductWidgetByIdParams } from '@/interfaces'
import { WidgetValidator } from '@/utils/widget-validation'
export class PerProductWidgetById extends Widget implements PerProductWidgetByIdParams {
widgetId: string
productId?: string
version?: 'v2'
constructor(params: WidgetConfig & PerProductWidgetByIdParams) {
super(params)
this.widgetId = params.widgetId
this.productId = params.productId
this.version = params.version
}
private get requestBody(): PerProductWidgetByIdParams {
return {
widgetId: this.widgetId,
productId: this.productId,
version: this.version,
}
}
async render(
options?: Partial<PerProductWidgetByIdParams>,
containerSelector?: string,
): Promise<void> {
const node = await this.renderToElement(options)
if (node) this.inject(node, containerSelector)
}
async renderToString(options?: Partial<PerProductWidgetByIdParams>): Promise<string> {
if (options) this.updateDefaults(options)
this.validateOptions()
const response = await this.api.fetchPerProductWidgetById(this.requestBody)
return response.data
}
async renderToElement(options?: Partial<PerProductWidgetByIdParams>): Promise<HTMLElement> {
const html = await this.renderToString(options)
return this.parseHtml(html)
}
private updateDefaults({ widgetId, productId, version }: Partial<PerProductWidgetByIdParams>) {
this.widgetId = widgetId ?? this.widgetId
this.productId = productId ?? this.productId
this.version = version ?? this.version
}
private validateOptions() {
return WidgetValidator.for('Per Product Widget')
.widgetId(this.widgetId)
.productId(this.productId)
.validate()
}
}