diff --git a/README.md b/README.md index ef27b0a..86b0c4c 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ A JavaScript library for transactional mutable updates ## Motivation +When we want to perform transactional updates on a mutable object, if an error is caught during the update process, the mutable update will not be applied at all. Otherwise, the mutable update will be applied to the mutable object. Therefore, we need a tool to implement this functionality. + ## Installation ```sh @@ -15,4 +17,46 @@ yarn add mutability ## Usage - +```ts +import { mutate } from 'mutability'; + +test('base - mutate', () => { + const baseState = { + a: { + c: 1, + }, + }; + mutate(baseState, (draft) => { + draft.a.c = 2; + }); + expect(baseState).toEqual({ a: { c: 2 } }); +}); + +test('base - mutate with error', () => { + const baseState = { + a: { + c: 1, + }, + b: { + c: 1, + }, + }; + try { + mutate(baseState, (draft) => { + draft.a.c = 2; + throw new Error('error'); + draft.b.c = 2; + }); + } catch (e) { + // + } + expect(baseState).toEqual({ + a: { + c: 1, + }, + b: { + c: 1, + }, + }); +}); +``` diff --git a/src/apply.ts b/src/apply.ts new file mode 100644 index 0000000..15c3da4 --- /dev/null +++ b/src/apply.ts @@ -0,0 +1,93 @@ +import { DraftType, Operation, Patches } from './interface'; +import { deepClone, get, getType, unescapePath } from './utils'; + +export function apply(state: any, patches: Patches) { + let i; + for (i = patches.length - 1; i >= 0; i -= 1) { + const { value, op, path } = patches[i]; + if ( + (!path.length && op === Operation.Replace) || + (path === '' && op === Operation.Add) + ) { + state = value; + break; + } + } + if (i > -1) { + patches = patches.slice(i + 1); + } + patches.forEach((patch) => { + const { path: _path, op } = patch; + const path = unescapePath(_path); + let base: any = state; + for (let index = 0; index < path.length - 1; index += 1) { + const parentType = getType(base); + let key = path[index]; + if (typeof key !== 'string' && typeof key !== 'number') { + key = String(key); + } + if ( + ((parentType === DraftType.Object || parentType === DraftType.Array) && + (key === '__proto__' || key === 'constructor')) || + (typeof base === 'function' && key === 'prototype') + ) { + throw new Error( + `Patching reserved attributes like __proto__ and constructor is not allowed.` + ); + } + // use `index` in Set draft + base = get( + getType(base) === DraftType.Set ? Array.from(base) : base, + key + ); + if (typeof base !== 'object') { + throw new Error(`Cannot apply patch at '${path.join('/')}'.`); + } + } + + const type = getType(base); + // ensure the original patch is not modified. + const value = deepClone(patch.value); + const key = path[path.length - 1]; + switch (op) { + case Operation.Replace: + switch (type) { + case DraftType.Map: + return base.set(key, value); + case DraftType.Set: + throw new Error(`Cannot apply replace patch to set.`); + default: + return (base[key] = value); + } + case Operation.Add: + switch (type) { + case DraftType.Array: + // If the "-" character is used to + // index the end of the array (see [RFC6901](https://datatracker.ietf.org/doc/html/rfc6902)), + // this has the effect of appending the value to the array. + return key === '-' + ? base.push(value) + : base.splice(key as number, 0, value); + case DraftType.Map: + return base.set(key, value); + case DraftType.Set: + return base.add(value); + default: + return (base[key] = value); + } + case Operation.Remove: + switch (type) { + case DraftType.Array: + return base.splice(key as number, 1); + case DraftType.Map: + return base.delete(key); + case DraftType.Set: + return base.delete(patch.value); + default: + return delete base[key]; + } + default: + throw new Error(`Unsupported patch operation: ${op}.`); + } + }); +} diff --git a/src/index.ts b/src/index.ts index e69de29..36f89d4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -0,0 +1,9 @@ +import { create } from 'mutative'; +import { apply } from './apply'; + +export const mutate = (baseState: T, recipe: (state: T) => void) => { + const [, patches] = create(baseState, recipe, { + enablePatches: true, + }); + apply(baseState, patches); +}; diff --git a/src/interface.ts b/src/interface.ts new file mode 100644 index 0000000..02693e8 --- /dev/null +++ b/src/interface.ts @@ -0,0 +1,20 @@ +export const Operation = { + Remove: 'remove', + Replace: 'replace', + Add: 'add', +} as const; + +export const enum DraftType { + Object, + Array, + Map, + Set, +} + +interface Patch { + op: (typeof Operation)[keyof typeof Operation]; + value?: any; + path: string | (string | number)[]; +} + +export type Patches = Patch[]; diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..209b73e --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,36 @@ +import { DraftType } from './interface'; + +export function unescapePath(path: string | (string | number)[]) { + if (Array.isArray(path)) return path; + return path + .split('/') + .map((_item) => _item.replace(/~1/g, '/').replace(/~0/g, '~')) + .slice(1); +} + +export function getType(target: any) { + if (Array.isArray(target)) return DraftType.Array; + if (target instanceof Map) return DraftType.Map; + if (target instanceof Set) return DraftType.Set; + return DraftType.Object; +} + +export function get(target: any, key: PropertyKey) { + return getType(target) === DraftType.Map ? target.get(key) : target[key]; +} + +function deepClone(target: T): T; +function deepClone(target: any) { + if (typeof target !== 'object' || target === null) return target; + if (Array.isArray(target)) return target.map(deepClone); + if (target instanceof Map) + return new Map( + Array.from(target.entries()).map(([k, v]) => [k, deepClone(v)]) + ); + if (target instanceof Set) return new Set(Array.from(target).map(deepClone)); + const copy = Object.create(Object.getPrototypeOf(target)); + for (const key in target) copy[key] = deepClone(target[key]); + return copy; +} + +export { deepClone }; diff --git a/test/index.test.ts b/test/index.test.ts index 6ebd531..7a32636 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,3 +1,41 @@ -test('', () => { - // +import { mutate } from '../src'; + +test('base - mutate', () => { + const baseState = { + a: { + c: 1, + }, + }; + mutate(baseState, (draft) => { + draft.a.c = 2; + }); + expect(baseState).toEqual({ a: { c: 2 } }); +}); + +test('base - mutate with error', () => { + const baseState = { + a: { + c: 1, + }, + b: { + c: 1, + }, + }; + try { + mutate(baseState, (draft) => { + draft.a.c = 2; + throw new Error('error'); + draft.b.c = 2; + }); + } catch (e) { + // + } + expect(baseState).toEqual({ + a: { + c: 1, + }, + b: { + c: 1, + }, + }); });