Skip to content

[Question] How to serialize query results? #2512

Description

@hugotox

Hello!

This might be an issue related to Svelte, but I still think is worth asking the difference, or why a knex query result is serializable and an objection is not.

Example on a +page.server.ts in Svelte:

import { Model } from 'objection'
import knex from 'knex'

const pg = knex({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: ['public'],
})

Model.knex(pg)

class User extends Model {
  static get tableName() {
    return 'users'
  }
}

export const load = async () => {
  const users = await User.query()
  return {
    users,
  }
}

The above code fails on Svelte with a Cannot stringify arbitrary non-POJOs error. I can circumvent this issue with users: users.map((u) => u.toJSON()), but seems inefficient for large resultsets.

What is most curious to me, is that a knex query works without parsing to JSON:

import knex from 'knex'

const pg = knex({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: ['public'],
})

export const load = async () => {
  const rawUsers = await pg.select('*').from('users')
  return {
    rawUsers,
  }
}

Any advice on how to properly use Objection in Svelte is highly appreciated 🙏

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions