Skip to content

Commit

Permalink
add auto key generation in snapshot if missing
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviergonz committed Feb 23, 2025
1 parent 3804c00 commit d785fb5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/mobx-bonsai/src/node/nodeTypeKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Dispose, disposeOnce } from "../utils/disposeOnce"
import { assertIsNode, node } from "./node"
import mitt from "mitt"
import { IsNever, MarkOptional } from "ts-essentials"
import { getGlobalConfig } from "../globalConfig"

/**
* A unique key indicating the type of a node. This constant is used internally to identify node types.
Expand Down Expand Up @@ -139,7 +140,7 @@ export interface NodeType<TNode extends NodeWithAnyType, TKey extends keyof TNod
*
* @param data The data.
*/
snapshot(data: MarkOptional<TNode, NodeTypeKey>): TNode
snapshot(data: MarkOptional<TNode, NodeTypeKey | TKey>): TNode

/**
* Retrieves the key associated with the given node.
Expand Down Expand Up @@ -310,10 +311,20 @@ export function nodeType<TNode extends NodeWithAnyType = never>(
}>()

const snapshot = (data: MarkOptional<TNode, NodeTypeKey>) => {
return {
const sn = {
...data,
[nodeTypeKey]: type,
} as TNode

// generate key if missing
if (nodeTypeObj.key !== undefined) {
const key = nodeTypeObj.getKey(sn)
if (key === undefined) {
;(sn as any)[nodeTypeObj.key] = getGlobalConfig().keyGenerator()
}
}

return sn
}

const nodeTypeObj: NodeType<TNode> = (data: MarkOptional<TNode, NodeTypeKey>) => {
Expand Down
11 changes: 11 additions & 0 deletions packages/mobx-bonsai/test/node/node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,14 @@ it("setting a plain value of an existing unique node should result in a single r
configure({ enforceActions: "always" })
}
})

test("auto generates key if missing in snapshot", () => {
type Todo = TNode<"todo", { id: string; title: string }>
using tTodo = nodeType<Todo>("todo").with({ key: "id" })

const node = tTodo.snapshot({
title: "Test Todo",
// id is omitted intentionally
})
expect(node.id).toBe("id-1")
})

0 comments on commit d785fb5

Please sign in to comment.