Skip to content

Commit

Permalink
fix: better ObjectSchema types
Browse files Browse the repository at this point in the history
  • Loading branch information
Zielak committed Feb 13, 2022
1 parent c0cc240 commit 37ba3b0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
16 changes: 10 additions & 6 deletions packages/client/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,19 @@ type CollectionCallback<T, K> = (instance: T, key: K) => void

export type SchemaChangeCallback = (changes: DataChange[]) => void

export interface ObjectSchema<T = Record<string, any>>
extends WithSchemaDefinition {
type ObjectSchemaColyBase<T> = {
onChange: SchemaChangeCallback
listen<K extends keyof T>(
propName: K,
callback: (value: T[K], previousValue: T[K]) => void
): () => void
}
type DirectPrimitiveOrSchemaObject<T> = {
[K in keyof T]?: T[K] extends object ? ObjectSchema<T[K]> : T[K]
}
export type ObjectSchema<T = Record<string, any>> = ObjectSchemaColyBase<T> &
DirectPrimitiveOrSchemaObject<T> &
WithSchemaDefinition

/**
* Client-side, could also be wrapped with array-like or map-like functions.
Expand Down Expand Up @@ -99,10 +104,9 @@ export type ClientGameStateProps = {

ui?: Map<string, string>
}
export type ClientGameState<MoreProps = Record<string, any>> =
ClientGameStateProps &
MoreProps &
ObjectSchema<ClientGameStateProps & MoreProps>
export type ClientGameState<MoreProps = Record<string, any>> = ObjectSchema<
ClientGameStateProps & MoreProps
>

export function isSchemaObject(o: unknown): o is Schema {
return (
Expand Down
37 changes: 37 additions & 0 deletions packages/client/test/schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { ObjectSchema } from "../src/schema"

type SubjectTop = {
name: string
idx: number
}

type SubjectProps = {
name: string
top?: SubjectTop
idx?: number
}

test("ObjectSchema", () => {
// Expect these types to not change and be valid
const subject: ObjectSchema<SubjectProps> = {
name: "Testing subject",
top: {
name: "Top of testing subject",
_definition: { schema: { name: "strig" } },
listen: (p, c) => () => {},
onChange: () => {},
},
_definition: { schema: { name: "strig" } },
listen: (p, c) => () => {},
onChange: () => {},
}

expect(typeof subject.name).toBe("string")

expect(() => subject.top.name).not.toThrow()
expect(() => {
subject.listen("name", (newName, previousName) => {
newName
})
}).not.toThrow()
})

0 comments on commit 37ba3b0

Please sign in to comment.