Type Error Classes missing from json-patch

Enforce stricter typings
This commit is contained in:
Marco Ramos
2017-03-27 07:26:35 -04:00
parent bb7d6b2d08
commit 09644d8ba8
2 changed files with 39 additions and 14 deletions

View File

@@ -4,36 +4,42 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace jsonpatch {
type OpPatch = AddPath | RemovePath | ReplacePath | MovePath | CopyPath | TestPath;
type OpPatch = AddPatch | RemovePatch | ReplacePatch | MovePatch | CopyPatch | TestPatch;
interface Patch {
op: string;
}
interface AddPath extends Patch {
path: string;
}
interface AddPatch extends Patch {
op: 'add';
value: any;
}
interface RemovePath extends Patch {
path: string;
interface RemovePatch extends Patch {
op: 'remove';
}
interface ReplacePath extends Patch {
path: string;
interface ReplacePatch extends Patch {
op: 'replace';
value: any;
}
interface MovePath extends Patch {
interface MovePatch extends Patch {
op: 'move';
from: string;
path: string;
}
interface CopyPath extends Patch {
interface CopyPatch extends Patch {
op: 'copy';
from: string;
path: string;
}
interface TestPath extends Patch {
path: string;
interface TestPatch extends Patch {
op: 'test';
value: any;
}
function apply(document: any, patches: OpPatch[]): any;
function compile(patches: OpPatch[]): (document: any) => any;
class JSONPatchError extends Error { }
class InvalidPointerError extends Error { }
class InvalidPatchError extends JSONPatchError { }
class PatchConflictError extends JSONPatchError { }
class PatchTestFailed extends Error { }
}
export = jsonpatch;

View File

@@ -32,3 +32,22 @@ jsonpatch.apply({ foo: 'bar' }, [{ op: 'test', path: '/foo', value: 'bar' }]);
jsonpatch.compile([{ op: 'test', path: '/foo', value: 'bar' }])({ foo: 'bar' });
jp.apply({}, [{ op: 'add', path: '/foo', value: 'bar' }]);
function patchShouldFail(document: any, patches: jsonpatch.OpPatch[]): string {
try {
jsonpatch.apply(document, patches);
throw new Error('Patch did not fail...');
} catch (err) {
if (err instanceof jsonpatch.PatchTestFailed) {
return 'Test failed';
} else if (err instanceof jsonpatch.InvalidPointerError) {
return 'Invalid Pointer';
} else if (err instanceof jsonpatch.InvalidPatchError) {
return 'Invalid Patch';
} else if (err instanceof jsonpatch.PatchConflictError) {
return 'Patch Conflict';
} else {
return 'Failed with unknown error';
}
}
}