Global scope?
Superjson is right now in a global scope - is there a design reason for this?
I'd see useage being like this
// utils/sj.ts
import {superjson} from 'superjson'
export const sj = superjson()
sj.registerClass( /* .. */)
// [..]
Or even rather, without modifiers after init. Could possibly open up for some nice typescript inference tricks
// utils/sj.ts
import {superjson} from 'superjson'
export const sj = superjson({
classes: [],
custom: [],
})
// elsewhere
sj.stringify(new MyCustomError('asdf');
is there a design reason for this?
Yes. Consider a custom class:
class BigBadassTrain {
chochoo() { }
}
SuperJSON.registerClass(BigBadassTrain)
If SuperJSON didn't have global state, there'd be no way for Blitz.js's instance to know about your class, and it would prevent it from being serialised in queries / mutations.
It would work exactly the same as long as there was one "singleton instance" created that was reused.
How would you go about making sure that all libraries use the same "singleton instance"?
Could possibly open up for some nice typescript inference tricks
Could you outline what improvements these could bring?
Let's say superjson gets very popular and several libs depend on it, for example - right now their "namespace" would collide.
- No unexpected side-effects / predictability
- Testing would probably be easier as you can instantiate a new instance in every test.
"namespace" would collide.
Oh, now I see. You mean two libraries registering a class called Foo?
Yes, that seems like a problem.
In my use case this would be super helpful, I currently need two superjson instances, one for serializing database models into a message queue, and one for serializing them into json objects for UI usage