add typing to qoi worker
This commit is contained in:
parent
c7d1a16d9f
commit
9dd199a4e3
16
frontend/src/app/workers/qoi-worker.dto.ts
Normal file
16
frontend/src/app/workers/qoi-worker.dto.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
export interface QOIImage {
|
||||
data: ImageData;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface QOIWorkerIn {
|
||||
id: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface QOIWorkerOut extends QOIImage {
|
||||
id: number;
|
||||
}
|
||||
|
||||
export type QOIJob = (url: string) => Promise<QOIImage>;
|
|
@ -1,11 +1,12 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
import { QOIImage, QOIJob, QOIWorkerOut } from './qoi-worker.dto';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class QoiWorkerService {
|
||||
private worker: Worker | null = null;
|
||||
private job: Promise<Function> | null = null;
|
||||
private job: Promise<QOIJob> | null = null;
|
||||
|
||||
constructor() {
|
||||
if (typeof Worker !== 'undefined') {
|
||||
|
@ -15,15 +16,11 @@ export class QoiWorkerService {
|
|||
}
|
||||
}
|
||||
|
||||
public async decode(url: string): Promise<{
|
||||
data: ImageData;
|
||||
width: number;
|
||||
height: number;
|
||||
}> {
|
||||
public async decode(url: string): Promise<QOIImage> {
|
||||
if (this.worker && !this.job) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = Date.now();
|
||||
const listener = ({ data }: { data: any }) => {
|
||||
const listener = ({ data }: { data: QOIWorkerOut }) => {
|
||||
if (data.id !== id) return;
|
||||
this.worker!.removeEventListener('message', listener);
|
||||
|
||||
|
|
|
@ -1,10 +1,7 @@
|
|||
import { QOIdecodeJS } from '../util/qoi/qoi-decode';
|
||||
import { QOIImage } from './qoi-worker.dto';
|
||||
|
||||
export default async function qoiDecodeJob(url: string): Promise<{
|
||||
data: ImageData;
|
||||
width: number;
|
||||
height: number;
|
||||
}> {
|
||||
export default async function qoiDecodeJob(url: string): Promise<QOIImage> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch image: ${url}`);
|
||||
|
|
|
@ -1,17 +1,20 @@
|
|||
/// <reference lib="webworker" />
|
||||
|
||||
import { QOIWorkerIn, QOIWorkerOut } from './qoi-worker.dto';
|
||||
import qoiDecodeJob from './qoi.job';
|
||||
|
||||
addEventListener('message', async (msg) => {
|
||||
const { id, url } = msg.data;
|
||||
const { id, url } = msg.data as QOIWorkerIn;
|
||||
if (!id || !url) {
|
||||
throw new Error('Invalid message');
|
||||
}
|
||||
|
||||
const result = await qoiDecodeJob(url);
|
||||
|
||||
postMessage({
|
||||
const returned: QOIWorkerOut = {
|
||||
id,
|
||||
...result,
|
||||
});
|
||||
};
|
||||
|
||||
postMessage(returned);
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue