superjson: Class object is not supported?

import {serialize} from 'superjson'

class A {
  constructor() {
    this.d = new Date()
  }
}

const a = new A()

console.log(serialize(a))
// -> { json: A { d: 2023-03-20T02:17:43.848Z } }
// why no meta? 

console.log(serialize({...a}))
// -> {
//   json: { d: '2023-03-20T02:17:43.848Z' },
//   meta: { values: { d: [Array] } }
// }

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Most upvoted comments

That makes sense, thank you! One solution you could think about is to write your own decorator (similar to @Entity) that wraps the SuperJSON.registerClass call:

function RegisterSuperJSON(klass) {
   SuperJSON.registerClass(klass)
   return klass
}

// ...

@RegisterSuperJSON
@Entity
class User { ... }

registerClass isn’t good choice if there’re many classes

Could you elaborate on your reasoning for this? If there’s something missing for usecases with a lot of classes, I’m happy to add that functionality to SuperJSON!

I use Typeorm to define tables in database. In API response, i return instance of entity class. If i have 100 tables in database, i must register 100 classes. So it’s inconvenient

Gotcha. Yeah, that will be hard to do with SuperJSON, sorry.

I got exactly the same issue when I used superjson with trpc and typeorm

registerClass isn’t good choice if there’re many classes

Could you elaborate on your reasoning for this? If there’s something missing for usecases with a lot of classes, I’m happy to add that functionality to SuperJSON!

Hi! You can use .registerClass for this. It’s not documented, sadly, but there’s a unit test that should explain it: https://github.com/blitz-js/superjson/blob/9d81c754ad64492499f4cf24371fc2fde5f99d96/src/index.test.ts#L784

A PR with a doc improvement would be very welcome 😃