Skip to content

Commit

Permalink
feat: add json patch generator
Browse files Browse the repository at this point in the history
  • Loading branch information
lukascivil committed Jul 28, 2023
1 parent 5c72f29 commit c7be77c
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/core/generate-json-patch.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Packages
import { getDiff } from '.'

// Models
import { JsonPatch } from '../models/jsondiffer.model'
import { generateJsonPatch } from './generate-json-patch'

describe('GenerateJsonPatch function', () => {
test('Should return the difference between two basic structures', () => {
const struct1 = { '0': [{ '0': 1 }] }
const struct2 = { '0': { '0': [1] } }
const expectedResult: Array<JsonPatch> = [
{ op: 'remove', path: '0/0' },
{ op: 'remove', path: '0/0/0[]' },
{ op: 'replace', path: '0', value: [] },
{ op: 'add', path: '0/0[]', value: {} },
{ op: 'add', path: '0/0[]/0', value: 1 }
]
const delta = getDiff(struct1, struct2)
const result = generateJsonPatch(delta)

expect(result).toEqual(expectedResult)
})

test('Should return the difference between two basic structures', () => {
const struct1 = {
baz: 'qux',
foo: 'bar'
}
const struct2 = {
baz: 'boo',
hello: ['world']
}
const expectedResult: Array<JsonPatch> = [
{
op: 'remove',
path: 'hello'
},
{
op: 'remove',
path: 'hello/0[]'
},
{
op: 'replace',
path: 'baz',
value: 'qux'
},
{
op: 'add',
path: 'foo',
value: 'bar'
}
]
const delta = getDiff(struct1, struct2)
const result = generateJsonPatch(delta)

expect(result).toEqual(expectedResult)
})
})
31 changes: 31 additions & 0 deletions src/core/generate-json-patch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Models
import { Delta, JsonPatch } from '../models/jsondiffer.model'

export const generateJsonPatch = (delta: Delta): Array<JsonPatch> => {
const operations: Array<JsonPatch> = []

delta.added.forEach((path) => {
operations.push({
op: 'remove',
path: path[0]
})
})

delta.edited.forEach((path) => {
operations.push({
op: 'replace',
path: path[0],
value: path[1]
})
})

delta.removed.forEach((path) => {
operations.push({
op: 'add',
path: path[0],
value: path[1]
})
})

return operations
}
19 changes: 19 additions & 0 deletions src/models/jsondiffer.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,22 @@ export interface Delta {
export interface JsonDiffOptions {
isLodashLike?: boolean
}

export interface JsonPatchRemove {
op: 'remove'
path: string
}

export interface JsonPatchReplace {
op: 'replace'
path: string
value: any
}

export interface JsonPatchAdd {
op: 'add'
path: string
value: any
}

export type JsonPatch = JsonPatchRemove | JsonPatchReplace | JsonPatchAdd

0 comments on commit c7be77c

Please sign in to comment.