Usage
To use Snapshotable, first make sure to install the package
pnpm add @rvoh/dream-plugin-json-snapshot
Once done, find the model you want to take snapshots with, and be sure to extend the parent model using the provided mixin:
import { Snapshotable } from '@rvoh/dream-plugin-json-snapshot'
class User extends Snapshotable(ApplicationModel) {
...
}
Once done, you can take a snapshot of a user like so:
const user = await User.firstOrFail()
const data = await user.takeSnapshot()
Including through associations
BelongsTo associations are intentionally skipped, as are through associations, so Snapshotable automatically avoids circuits (which would lead to an infinite loop). To explicitly include a through association, decorate it with the @SnapshotableFollowThrough() decorator.
const deco = new Decorators<typeof Host>()
export default class Host extends ApplicationModel {
@deco.HasMany('HostPlace')
public hostPlaces: HostPlace[]
@SnapshotableFollowThrough()
@deco.HasMany('Place', { through: 'hostPlaces' })
public places: Place[]
}
Filtering out unwanted columns and associations
@SnapshotableIgnore() works on both columns and associations. Use it to exclude anything you don't want in the snapshot output:
class User extends Snapshotable(ApplicationModel) {
@SnapshotableIgnore()
public passwordDigest: DreamColumn<User, 'passwordDigest'> // column excluded
@SnapshotableIgnore()
@deco.HasMany('Pet')
public pets: Pet[] // association excluded
}
Associations with a DreamConst.required or DreamConst.passthrough and-clause must be decorated with @SnapshotableIgnore(). Snapshotable cannot preload these associations without a runtime value they require, so takeSnapshot() throws if it encounters one that hasn't been excluded:
// Without @SnapshotableIgnore, takeSnapshot() throws at runtime
@SnapshotableIgnore()
@deco.HasMany('Post', { and: { status: DreamConst.required } })
public postsByStatus: Post[]