2021年3月6日星期六

How to cast a plain object as a instance of another type in JavaScript

I'm trying to store a session on disk for local development, and I'm running into a problem where the application expects me to return an instance of a Session and not an Object

function storeCallback(session) {    console.log("storeCallback ", session);    fs.writeFileSync("./session.json", JSON.stringify(session));    return true;  }    function loadCallback(id) {    console.log("loadCallback ", id);    const session = fs.readFileSync("./session.json", "utf8");    return JSON.parse(session);  }  

The session look like this:

Session {     id: '0984e7db-ad80-4276-966d-9db54fac11c2',     shop: 'swiftnextstep.myshopify.com',     state: '113617456401679',     isOnline: true   }  

Once I save and read back, it looks like this

 {     id: '0984e7db-ad80-4276-966d-9db54fac11c2',     shop: 'swiftnextstep.myshopify.com',     state: '113617456401679',     isOnline: true   }  

And I get an error InternalServerError: Expected return to be instance of Session, but received instance of Object.

How can I cast/transform the object I'm parsing from storage into the expected Session type?

https://stackoverflow.com/questions/66512943/how-to-cast-a-plain-object-as-a-instance-of-another-type-in-javascript March 07, 2021 at 11:30AM

没有评论:

发表评论