Return encode result from Image.encode calls

Before this, there were one way to use the API:
call `await image.encode({ mozjpeg: {} })`
then use `encodedWith` by asserting that `mozjpeg` property exists on it

After adding return value to encode, people
will be able to use it like
`const { mozjpeg } = await image.encode({ mozjpeg: {} });`
which provides better type safety
This commit is contained in:
ergunsh
2021-09-10 14:45:20 +02:00
parent 6bfce29af6
commit 914cdea41d

View File

@@ -32,6 +32,14 @@ type EncodeResult = {
extension: string; extension: string;
size: number; size: number;
}; };
type EncoderOptions = {
mozjpeg?: Partial<MozJPEGEncodeOptions>;
webp?: Partial<WebPEncodeOptions>;
avif?: Partial<AvifEncodeOptions>;
jxl?: Partial<JxlEncodeOptions>;
wp2?: Partial<WP2EncodeOptions>;
oxipng?: Partial<OxiPngEncodeOptions>;
};
async function decodeFile({ async function decodeFile({
file, file,
@@ -221,19 +229,12 @@ class Image {
* @param {object} encodeOptions - An object with encoders to use, and their settings. * @param {object} encodeOptions - An object with encoders to use, and their settings.
* @returns {Promise<void>} - A promise that resolves when the image has been encoded with all the specified encoders. * @returns {Promise<void>} - A promise that resolves when the image has been encoded with all the specified encoders.
*/ */
async encode( async encode<T extends EncoderOptions>(
encodeOptions: { encodeOptions: {
optimizerButteraugliTarget?: number; optimizerButteraugliTarget?: number;
maxOptimizerRounds?: number; maxOptimizerRounds?: number;
} & { } & T,
mozjpeg?: Partial<MozJPEGEncodeOptions>; ): Promise<{ [key in keyof T]: EncodeResult }> {
webp?: Partial<WebPEncodeOptions>;
avif?: Partial<AvifEncodeOptions>;
jxl?: Partial<JxlEncodeOptions>;
wp2?: Partial<WP2EncodeOptions>;
oxipng?: Partial<OxiPngEncodeOptions>;
} = {},
): Promise<void> {
const { bitmap } = await this.decoded; const { bitmap } = await this.decoded;
for (const [name, options] of Object.entries(encodeOptions)) { for (const [name, options] of Object.entries(encodeOptions)) {
if (!Object.keys(encoders).includes(name)) { if (!Object.keys(encoders).includes(name)) {
@@ -257,6 +258,7 @@ class Image {
}); });
} }
await Promise.all(Object.values(this.encodedWith)); await Promise.all(Object.values(this.encodedWith));
return this.encodedWith as { [key in keyof T]: EncodeResult };
} }
} }