Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional handlers config #8

Merged
merged 6 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,47 @@ With `typed-path` typescript can check paths and warns you about errors.

![](http://res.cloudinary.com/daren64mz/image/upload/v1487457505/tp-refactoring_p4byr3.gif)

Also you can get access to the path string using `$path` special field. [@m-abboud](https://github.com/m-abboud)
#### .$path
[@m-abboud](https://github.com/m-abboud)
Also you can get access to the path string using `$path` special field.

Like this:
```js
console.log(tp<TestType>().a.b.c.d.$path); // this will output "a.b.c.d"
```

If you need a raw path, which is of type `string[]` - you can get it using `$raw` special field. [dcbrwn](https://github.com/dcbrwn)
#### .$raw
[@dcbrwn](https://github.com/dcbrwn)
If you need a raw path, which is of type `string[]` - you can get it using `$raw` special field.
```js
console.log(tp<TestType>().a.b.c.d.$raw); // this will output ["a", "b", "c", "d"]
```

#### Additional handlers
[@nick-lvov-dev](https://github.com/nick-lvov-dev)

You can extend path handlers functionality using additional handlers:

```js
const testAdditionalHandlers = {
$url: (path: string[]) => path.join('/')
}

console.log(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$url); // this will output "a/b/c"
```

The additional handlers are also chainable:

```js
const testAdditionalHandlers = {
$abs: (path: string[]) => typedPath<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers, ['', ...path]),
$url: (path: string[]) => path.join('/')
}

console.log(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$abs.$url); // this will output "/a/b/c"
```

---

### Suggestions

Expand Down
13 changes: 13 additions & 0 deletions index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ type TestType = {
}
};

const testAdditionalHandlers = {
$abs: (path: string[]) => typedPath<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers, ['', ...path]),
$url: (path: string[]) => path.join('/')
}

describe('Typed path', () => {
it('should get field path', () => {
expect(typedPath<TestType>().a.b.c.$path).to.equal('a.b.c');
Expand Down Expand Up @@ -60,4 +65,12 @@ describe('Typed path', () => {
it('should get path for valueOf()', () => {
expect(tp<TestType>().a.b.f[3].blah.path.valueOf()).to.equal('a.b.f[3].blah.path');
});

it('should work with extended handlers', () => {
expect(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$url).to.equal('a/b/c');
})

it('should work with chained extended handlers', () => {
expect(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$abs.$url).to.equal('/a/b/c');
})
});
81 changes: 42 additions & 39 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,61 +1,64 @@
export type TypedPathKey = string | symbol | number;
function pathToString(path: string[]): string {
return path.reduce((current, next) => {
if (+next === +next) {
current += `[${next}]`;
} else {
current += current === '' ? `${next}` : `.${next}`;
}

export type TypedPathNode<T> = {
$path: string;
$raw: TypedPathKey[];
};
return current;
}, '');
}

export type TypedPathKey = string | symbol | number;

export type TypedPathFunction<T> = (...args: any[]) => T;

export type TypedPathWrapper<T> = (T extends Array<infer Z>
export type TypedPathHandlersConfig = Record<string, <T extends TypedPathHandlersConfig = Record<never, never>>(path: string[], additionalHandlers?: T) => any>;

const defaultHandlersConfig = {
$path: (path: string[]) => pathToString(path),
$raw: (path: string[]) => path,
toString: (path: string[]) => () => pathToString(path),
[Symbol.toStringTag]: (path: string[]) => () => pathToString(path),
valueOf: (path: string[]) => () => pathToString(path),
}

export type TypedPathHandlers<T extends TypedPathHandlersConfig> = {
[key in keyof T]: ReturnType<T[key]>;
};

export type TypedPathWrapper<T, TPH extends TypedPathHandlers<Record<never, never>>> = (T extends Array<infer Z>
? {
[index: number]: TypedPathWrapper<Z>;
[index: number]: TypedPathWrapper<Z, TPH>;
}
: T extends TypedPathFunction<infer RET>
? {
(): TypedPathWrapper<RET>;
(): TypedPathWrapper<RET, TPH>;
} & {
[P in keyof RET]: TypedPathWrapper<RET[P]>;
[P in keyof RET]: TypedPathWrapper<RET[P], TPH>;
}
: {
[P in keyof T]: TypedPathWrapper<T[P]>;
}
) & TypedPathNode<T>;

const toStringMethods: (string | symbol | number)[] = [
'toString',
Symbol.toStringTag,
'valueOf'
];

function pathToString(path: string[]): string {
return path.reduce((current, next) => {
if (+next === +next) {
current += `[${next}]`;
} else {
current += current === '' ? `${next}` : `.${next}`;
[P in keyof T]: TypedPathWrapper<T[P], TPH>;
}
) & TypedPathHandlers<TPH>;

return current;
}, '');
}

export function typedPath<T>(path: string[] = []): TypedPathWrapper<T> {
return <TypedPathWrapper<T>>new Proxy({}, {
export function typedPath<T, K extends TypedPathHandlersConfig = Record<never, never>>(additionalHandlers?: K, path: string[] = [], defaultsApplied: boolean = false): TypedPathWrapper<T, K & typeof defaultHandlersConfig> {
return <TypedPathWrapper<T, K & typeof defaultHandlersConfig>>new Proxy({}, {
get(target: T, name: TypedPathKey) {
if (name === '$path') {
return pathToString(path);
}
let handlersConfig: TypedPathHandlersConfig;

if (name === '$raw') {
return path;
if (defaultsApplied) {
handlersConfig = additionalHandlers;
} else {
handlersConfig = { ...(additionalHandlers ?? {}), ...defaultHandlersConfig };
}

if (toStringMethods.includes(name)) {
return () => pathToString(path);
if (handlersConfig.hasOwnProperty(name)) {
return handlersConfig[name as any](path, additionalHandlers);
}

return typedPath([...path, name.toString()]);
return typedPath(handlersConfig, [...path, name.toString()], true);
}
});
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "typed-path",
"version": "2.0.2",
"version": "2.1.0",
"description": "Type safe object string paths for typescript.",
"main": "index.js",
"repository": {
Expand Down Expand Up @@ -39,8 +39,8 @@
"chai": "^3.5.0",
"husky": "^0.13.1",
"mocha": "^6.2.0",
"ts-node": "8.3.0",
"ts-node": "^9.0.0",
"tslint": "^4.4.2",
"typescript": "3.6.4"
"typescript": "^4.0.5"
}
}
30 changes: 15 additions & 15 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -920,10 +920,10 @@ slide@^1.1.5:
version "1.1.6"
resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707"

source-map-support@^0.5.6:
version "0.5.13"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932"
integrity sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==
source-map-support@^0.5.17:
version "0.5.19"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61"
integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==
dependencies:
buffer-from "^1.0.0"
source-map "^0.6.0"
Expand Down Expand Up @@ -1034,16 +1034,16 @@ timed-out@^3.0.0:
version "3.1.3"
resolved "https://registry.yarnpkg.com/timed-out/-/timed-out-3.1.3.tgz#95860bfcc5c76c277f8f8326fd0f5b2e20eba217"

ts-node@8.3.0:
version "8.3.0"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-8.3.0.tgz#e4059618411371924a1fb5f3b125915f324efb57"
integrity sha512-dyNS/RqyVTDcmNM4NIBAeDMpsAdaQ+ojdf0GOLqE6nwJOgzEkdRNzJywhDfwnuvB10oa6NLVG1rUJQCpRN7qoQ==
ts-node@^9.0.0:
version "9.0.0"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-9.0.0.tgz#e7699d2a110cc8c0d3b831715e417688683460b3"
integrity sha512-/TqB4SnererCDR/vb4S/QvSZvzQMJN8daAslg7MeaiHvD8rDZsSfXmNeNumyZZzMned72Xoq/isQljYSt8Ynfg==
dependencies:
arg "^4.1.0"
diff "^4.0.1"
make-error "^1.1.1"
source-map-support "^0.5.6"
yn "^3.0.0"
source-map-support "^0.5.17"
yn "3.1.1"

tslint@^4.4.2:
version "4.4.2"
Expand All @@ -1066,10 +1066,10 @@ type-detect@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-1.0.0.tgz#762217cc06db258ec48908a1298e8b95121e8ea2"

typescript@3.6.4:
version "3.6.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.6.4.tgz#b18752bb3792bc1a0281335f7f6ebf1bbfc5b91d"
integrity sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg==
typescript@^4.0.5:
version "4.0.5"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.5.tgz#ae9dddfd1069f1cb5beb3ef3b2170dd7c1332389"
integrity sha512-ywmr/VrTVCmNTJ6iV2LwIrfG1P+lv6luD8sUJs+2eI9NLGigaN+nUQc13iHqisq7bra9lnmUSYqbJvegraBOPQ==

unzip-response@^1.0.2:
version "1.0.2"
Expand Down Expand Up @@ -1196,7 +1196,7 @@ [email protected], yargs@^13.3.0:
y18n "^4.0.0"
yargs-parser "^13.1.1"

yn@^3.0.0:
yn@3.1.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50"
integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==