Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: Add null check and type guard for window.fejson access #49

Open
strawmelonjuice opened this issue Nov 27, 2024 · 0 comments
Open

Comments

@strawmelonjuice
Copy link
Owner

strawmelonjuice commented Nov 27, 2024

The function could benefit from stronger type safety when accessing window.fejson.

 export function getJsonObj() {
-	if (!window.fejson) {
+	if (!window.fejson || !isFejsonObject(window.fejson)) {
 		return {
 			instance_iid: -1,
 			instance_lastsync: -1,
 			pulled: 0,
 			user_id: -1,
 			user_username: "unset",
 			user_email: "unset",
 		};
 	}
 	return {
 		instance_iid: window.fejson.instance.iid,
 		instance_lastsync: window.fejson.instance.lastsync,
 		pulled: window.fejson.pulled,
 		user_id: window.fejson.user.id,
 		user_username: window.fejson.user.username,
 		user_email: window.fejson.user.email,
 	};
 }

+function isFejsonObject(obj: any): obj is fejsonObject {
+    return obj &&
+        typeof obj.pulled === 'number' &&
+        obj.instance &&
+        typeof obj.instance.iid === 'string' &&
+        typeof obj.instance.lastsync === 'number' &&
+        obj.user &&
+        typeof obj.user.username === 'string' &&
+        typeof obj.user.id === 'number' &&
+        typeof obj.user.email === 'string';
+}

Committable suggestion skipped: line range outside the PR's diff.

Originally posted by @coderabbitai[bot] in #47 (comment)

@strawmelonjuice strawmelonjuice changed the title _:hammer_and_wrench: Refactor suggestion_ Refactor: Add null check and type guard for window.fejson access Nov 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant