fix: Preserve existing values when optional update fields are omitted (#14344)

* fix: Preserve existing values when optional update fields are omitted

* chore: Rename setDefined to fill

* chore: Use fill in users.update and teamUpdater
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-26 17:29:17 -04:00
1 parent ce439c893c
commit 9fe0c7ba2b
18 files changed
+275 -136

No files matched your search

+35
View File
@@ -1,10 +1,12 @@
import { faker } from "@faker-js/faker";
import { randomUUID } from "node:crypto";
import { CommentingAccess, TeamPreference } from "@shared/types";
import { createContext } from "@server/context";
import {
buildDocument,
buildSearchQuery,
buildTeam,
buildUser,
} from "@server/test/factories";
import SearchQuery from "../SearchQuery";
import User from "../User";
@@ -57,6 +59,39 @@ describe("Model", () => {
});
});
describe("fill", () => {
it("should skip undefined values", async () => {
const team = await buildTeam({ name: "Test Team", guestSignin: true });
team.fill({ name: undefined, guestSignin: false });
expect(team.name).toEqual("Test Team");
expect(team.guestSignin).toEqual(false);
expect(team.changed()).toEqual(["guestSignin"]);
});
it("should set null values", async () => {
const team = await buildTeam({ avatarUrl: "https://example.com/a.png" });
team.fill({ avatarUrl: null });
expect(team.avatarUrl).toBeNull();
});
});
describe("updateWithCtx", () => {
it("should not clear attributes with undefined values", async () => {
const team = await buildTeam({ name: "Test Team" });
const user = await buildUser({ teamId: team.id });
await team.updateWithCtx(createContext({ user }), {
name: undefined,
guestSignin: false,
});
await team.reload();
expect(team.name).toEqual("Test Team");
expect(team.guestSignin).toEqual(false);
});
});
describe("batch load", () => {
it("should return data in batches", async () => {
const team = await buildTeam();
+14 -2
View File
@@ -1,4 +1,5 @@
import isEqual from "fast-deep-equal";
import { isUndefined, omitBy } from "es-toolkit";
import { isArray, isObject, pick } from "es-toolkit/compat";
import type {
Attributes,
@@ -83,7 +84,7 @@ class Model<
}
/**
* This is the same as calling `set` and then calling `save`.
* This is the same as calling `fill` and then calling `save`.
*/
public updateWithCtx(
ctx: APIContext,
@@ -97,10 +98,21 @@ class Model<
publish: true,
},
};
this.set(keys);
this.fill(keys);
return this.save(hookContext);
}
/**
* Sets the given attributes on the instance, skipping any with an undefined
* value. Use `null` to clear an attribute.
*
* @param keys the attributes to set.
* @returns the instance.
*/
public fill(keys: Partial<TModelAttributes>) {
return this.set(omitBy(keys, isUndefined));
}
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will
* either be completely deleted, or have its deletedAt timestamp set to the current time.