Skip to content

Commit

Permalink
Add util for handling unsafe logics
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Feb 14, 2025
1 parent 30b0045 commit effad35
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
7 changes: 3 additions & 4 deletions apps/blog/src/plugins/lib/rehypeImageMetaData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Processor } from "unified";
import type { Node } from "unist";
import type { VFile } from "vfile";
import { imageSize } from "image-size";
import { unsafe } from "@marshallku/utils";
import type { ImageNode } from "#plugins/types";

function isExternalImage(path: string) {
Expand All @@ -18,16 +19,14 @@ function addImageMetaData(node: ImageNode) {
return;
}

try {
unsafe(() => {
const dimensions = imageSize(`public${decodeURIComponent(src)}`);

if (dimensions) {
node.properties.width = dimensions.width;
node.properties.height = dimensions.height;
}
} catch (err) {
console.error(`Failed to get image dimensions for ${src}`);
}
}, true);
}

export default function rehypeImageMetaData(this: Processor) {
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export * from "./lib/object";
export * from "./lib/query";
export * from "./lib/random";
export { default as to } from "./lib/to";
export { default as unsafe } from "./lib/unsafe";
export * from "./lib/url";
19 changes: 19 additions & 0 deletions packages/utils/src/lib/unsafe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Runs the given function, and ignores any errors that may occur.
*/
export default function unsafe<T>(
fn: () => T,
logErrorOrExecute: boolean | ((error: unknown) => void) = false,
): T | null {
try {
return fn();
} catch (error) {
if (typeof logErrorOrExecute === "function") {
logErrorOrExecute(error);
} else if (!logErrorOrExecute) {
console.error(error);
}

return null;
}
}

1 comment on commit effad35

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Visual regression test result - success

Component Story Success Viewport MisMatch Percentage
components-button string-children phone 0.00%
components-button string-children tablet 0.10%
input-input default phone 0.00%
input-input default tablet 0.10%
input-input line phone 0.00%
input-input line tablet 0.04%
input-input box phone 0.00%
input-input box tablet 0.04%
components-profile default phone 0.00%
components-profile default tablet 0.00%
input-textarea line phone 0.00%
input-textarea line tablet 0.04%
input-textarea box phone 0.00%
input-textarea box tablet 0.04%
typography-typography default phone 0.00%
typography-typography default tablet 0.07%

Please sign in to comment.