Skip to content

Commit

Permalink
feat(base): implement transactional updates
Browse files Browse the repository at this point in the history
  • Loading branch information
unadlib committed Feb 23, 2024
1 parent d07ed0c commit 78c6b71
Show file tree
Hide file tree
Showing 6 changed files with 243 additions and 3 deletions.
46 changes: 45 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
},
});
});
```
93 changes: 93 additions & 0 deletions src/apply.ts
Original file line number Diff line number Diff line change
@@ -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}.`);
}
});
}
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { create } from 'mutative';
import { apply } from './apply';

export const mutate = <T>(baseState: T, recipe: (state: T) => void) => {
const [, patches] = create(baseState, recipe, {
enablePatches: true,
});
apply(baseState, patches);
};
20 changes: 20 additions & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
@@ -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[];
36 changes: 36 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -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<T>(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 };
42 changes: 40 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
@@ -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,
},
});
});

0 comments on commit 78c6b71

Please sign in to comment.