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

feat: enable nested routers by introducing RecursivelyProcessAppRouter #138

Merged
merged 3 commits into from
Jan 22, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/popular-bikes-greet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ts-rest/core': minor
---

Enable nested routers without declaring new constants
23 changes: 16 additions & 7 deletions libs/ts-rest/core/src/lib/dsl.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { Narrow } from './type-utils';

/**
* The path with colon-prefixed parameters
* e.g. "/posts/:id".
Expand Down Expand Up @@ -37,6 +35,19 @@ export type AppRouteMutation = {
responses: Record<number, unknown>;
};

/**
* Recursively process a router, allowing for you to define nested routers.
*
* The main purpose of this is to convert all path strings into string constants so we can infer the path
*/
type RecursivelyProcessAppRouter<T extends AppRouter> = {
[K in keyof T]: T[K] extends AppRoute
? T[K]
: T[K] extends AppRouter
? RecursivelyProcessAppRouter<T[K]>
: T[K];
};

/**
* A union of all possible endpoint types.
*/
Expand Down Expand Up @@ -67,17 +78,17 @@ type ContractInstance = {
/**
* A collection of routes or routers
*/
router: <T extends AppRouter>(endpoints: Narrow<T>) => T;
router: <T extends AppRouter>(endpoints: RecursivelyProcessAppRouter<T>) => T;
/**
* A single query route, should exist within
* a {@link AppRouter}
*/
query: <T extends AppRouteQuery>(query: Narrow<T>) => T;
query: <T extends AppRouteQuery>(query: T) => T;
/**
* A single mutation route, should exist within
* a {@link AppRouter}
*/
mutation: <T extends AppRouteMutation>(mutation: Narrow<T>) => T;
mutation: <T extends AppRouteMutation>(mutation: T) => T;
/**
* Exists to allow storing a Type in the contract (at compile time only)
*/
Expand All @@ -103,9 +114,7 @@ export const initContract = (): ContractInstance => {
return {
// @ts-expect-error - this is a type error, but it's not clear how to fix it
router: (args) => args,
// @ts-expect-error - this is a type error, but it's not clear how to fix it
query: (args) => args,
// @ts-expect-error - this is a type error, but it's not clear how to fix it
mutation: (args) => args,
response: <T>() => undefined as unknown as T,
body: <T>() => undefined as unknown as T,
Expand Down
36 changes: 1 addition & 35 deletions libs/ts-rest/core/src/lib/type-utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { z } from 'zod';
import { getValue, ZodInferOrType } from './type-utils';
import { ZodInferOrType } from './type-utils';

const zodObject = z.object({ title: z.string() });
type Test1 = ZodInferOrType<typeof zodObject>;
Expand All @@ -11,37 +11,3 @@ type Test2 = ZodInferOrType<typeof zodObject>;
type Test3 = ZodInferOrType<{ title: string }>;

it.todo('should infer type');

describe('getValue', () => {
it('should get one level deep', () => {
const obj = {
title: 'Title',
};

const value = getValue(obj, 'title');

expect(value).toBe('Title');
});

it('should get one level deep with nullable', () => {
const obj = {
title: 'Title',
};

const value = getValue(obj, 'test', null);

expect(value).toBe(null);
});

it('should get two levels deep', () => {
const obj = {
sub: {
text: 'text',
},
};

const value = getValue(obj, 'sub.text');

expect(value).toBe('text');
});
});
35 changes: 0 additions & 35 deletions libs/ts-rest/core/src/lib/type-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,26 +37,6 @@ export type GetFieldType<T, P> = P extends `${infer Left}.${infer Right}`
: undefined
: undefined;

export function getValue<
TData,
TPath extends string,
TDefault = GetFieldType<TData, TPath>
>(
data: TData,
path: TPath,
defaultValue?: TDefault
): GetFieldType<TData, TPath> | TDefault {
const value = path
.split(/[.[\]]/)
.filter(Boolean)
.reduce<GetFieldType<TData, TPath>>(
(value, key) => (value as any)?.[key],
data as any
);

return value !== undefined ? value : (defaultValue as TDefault);
}

// https://stackoverflow.com/questions/63447660/typescript-remove-all-properties-with-particular-type
// Nested solution also available ^
type ExcludeKeysWithTypeOf<T, V> = {
Expand All @@ -74,21 +54,6 @@ export type ZodInferOrType<T> = T extends ZodTypeAny ? z.infer<T> : T;

export type Merge<T, U> = Omit<T, keyof U> & U;

type Try<A, B, C> = A extends B ? A : C;

type NarrowRaw<T> =
// eslint-disable-next-line @typescript-eslint/ban-types
| (T extends Function ? T : never)
| (T extends string | number | bigint | boolean ? T : never)
| (T extends [] ? [] : never)
| {
[K in keyof T]: K extends 'description' ? T[K] : NarrowNotZod<T[K]>;
};

type NarrowNotZod<T> = Try<T, ZodType, NarrowRaw<T>>;

export type Narrow<T> = Try<T, [], NarrowNotZod<T>>;

export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

// https://github.com/ts-essentials/ts-essentials/blob/4c451652ba7c20b0e0b965e0b7755fd4d7844127/lib/types.ts#L228
Expand Down
35 changes: 35 additions & 0 deletions libs/ts-rest/express/src/lib/ts-rest-express.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { getValue } from './ts-rest-express';

describe('getValue', () => {
it('should get one level deep', () => {
const obj = {
title: 'Title',
};

const value = getValue(obj, 'title');

expect(value).toBe('Title');
});

it('should get one level deep with nullable', () => {
const obj = {
title: 'Title',
};

const value = getValue(obj, 'test', null);

expect(value).toBe(null);
});

it('should get two levels deep', () => {
const obj = {
sub: {
text: 'text',
},
};

const value = getValue(obj, 'sub.text');

expect(value).toBe('text');
});
});
22 changes: 21 additions & 1 deletion libs/ts-rest/express/src/lib/ts-rest-express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,34 @@ import {
AppRouteQuery,
AppRouter,
checkZodSchema,
getValue,
GetFieldType,
isAppRoute,
parseJsonQueryObject,
PathParamsWithCustomValidators,
Without,
ZodInferOrType,
} from '@ts-rest/core';

export function getValue<
TData,
TPath extends string,
TDefault = GetFieldType<TData, TPath>
>(
data: TData,
path: TPath,
defaultValue?: TDefault
): GetFieldType<TData, TPath> | TDefault {
const value = path
.split(/[.[\]]/)
.filter(Boolean)
.reduce<GetFieldType<TData, TPath>>(
(value, key) => (value as any)?.[key],
data as any
);

return value !== undefined ? value : (defaultValue as TDefault);
}

export type ApiRouteResponse<T> = {
[K in keyof T]: {
status: K;
Expand Down