Skip to content

Commit

Permalink
Remove validator
Browse files Browse the repository at this point in the history
  • Loading branch information
aquapi committed Jul 7, 2024
1 parent 09a8f41 commit 4fb6f15
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 106 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bit-js/byte",
"version": "1.6.1",
"version": "2.0.0-alpha.1",
"module": "index.js",
"devDependencies": {
"@types/bun": "latest",
Expand Down
9 changes: 2 additions & 7 deletions src/core/client/types/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { BaseRoute, GenericResponse, RoutesRecord } from '../../server';
import type { BaseRoute, RoutesRecord } from '../../server';
import type { Promisify, RequiredKeys, AwaitedReturn } from '../../utils/types';
import type { RequestBaseProps, RequestProps } from './requestProps';

Expand All @@ -9,12 +9,7 @@ type RouteFunc<Path extends string, Init, Return> =
? (path: Path, init?: RequestBaseProps) => Return
: (path: Path, init: Init) => Return;

type InferReturn<T extends BaseRoute> = Promisify<AwaitedReturn<T['handler']> | Extract<(
// Get all response return type from validators
T['validator'] extends null ? never : {
[K in T['validator']]: AwaitedReturn<T['validator'][K]>
}[string]
), GenericResponse>>;
type InferReturn<T extends BaseRoute> = Promisify<AwaitedReturn<T['handler']>>;

export type InferRoute<T extends BaseRoute> = {
[K in T['method']]: RouteFunc<
Expand Down
2 changes: 0 additions & 2 deletions src/core/client/utils/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ const objectSerializers: Record<string, Serializer> = {
export default function serialize(input: any) {
switch (typeof input) {
case 'string': return input;

case 'object': return input === null ? null : objectSerializers[input.constructor.name]?.(input) ?? input

case 'number': return `${input}`;
case 'bigint': return `${input}`;
case 'boolean': return `${input}`;
Expand Down
52 changes: 16 additions & 36 deletions src/core/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Blitz, { BaseRouter } from '@bit-js/blitz';
import type { ProtoSchema, RequestMethod } from '../utils/methods';

import { Route, type RoutesRecord } from './route';
import type { InferValidatorRecord, ValidatorRecord } from './types/validator';
import { Context, type BaseHandler, type DeferFn, type Fn } from './types/handler';

import { bit } from '../client';
Expand All @@ -16,21 +15,19 @@ import type { GenericResponse } from './utils/responses';
interface Register<Method extends string, T extends RoutesRecord, State> {
<
const Path extends string,
const Validator extends ValidatorRecord<Path>,
const Handler extends BaseHandler<Path, State, InferValidatorRecord<Validator>>,
const Handler extends BaseHandler<Path, State>,
>(
path: Path,
validator: Validator,
handler: Handler
): Byte<[...T, Route<Method, Path, Validator, Handler>], State>;
): Byte<[...T, Route<Method, Path, Handler>], State>;

<
const Path extends string,
const Handler extends BaseHandler<Path, State>,
>(
path: Path,
handlers: Handler
): Byte<[...T, Route<Method, Path, null, Handler>], State>;
): Byte<[...T, Route<Method, Path, Handler>], State>;
};

type HandlerRegisters<T extends RoutesRecord, State> = {
Expand Down Expand Up @@ -70,17 +67,17 @@ export class Byte<Rec extends RoutesRecord = [], State = {}> implements ProtoSch
/**
* Bind a prop to the context
*/
set<Name extends string, Getter extends Fn<State>>(name: Name, fn: Getter): Byte<Rec, State & { [K in Name]: AwaitedReturn<Getter> }> {
set<Name extends string, Getter extends Fn<State>>(name: Name, fn: Getter) {
this.actions.push($set(name, fn));
return this as any;
return this as Byte<Rec, State & { [K in Name]: AwaitedReturn<Getter> }>;
}

/**
* Bind a prop to the context
*/
state<Name extends string, Getter extends Fn<State>>(name: Name, fn: Getter): Byte<Rec, State & { [K in Name]: Exclude<AwaitedReturn<Getter>, GenericResponse> }> {
state<Name extends string, Getter extends Fn<State>>(name: Name, fn: Getter) {
this.actions.push($state(name, fn));
return this as any;
return this as Byte<Rec, State & { [K in Name]: Exclude<AwaitedReturn<Getter>, GenericResponse> }>;
}

/**
Expand Down Expand Up @@ -126,7 +123,7 @@ export class Byte<Rec extends RoutesRecord = [], State = {}> implements ProtoSch
*/
build(router: BaseRouter = new Blitz()) {
const { routes } = this;
router.fallback ??= default404;
router.fallback = default404;

for (let i = 0, { length } = routes; i < length; ++i)
routes[i].register(router);
Expand Down Expand Up @@ -157,35 +154,19 @@ export class Byte<Rec extends RoutesRecord = [], State = {}> implements ProtoSch

// Push new route
this.routes.push(
typeof args[0] === 'function'
? new Route(
method, path,
// Check for validator
null, args[0],
// Load the actions and alters
actions.length === 0 ? emptyList : [actions],
defers.length === 0 ? emptyList : [defers]
)
: new Route(
method, path,
// Check for validator
args[0], args[1],
// Load the actions and alters
actions.length === 0 ? emptyList : [actions],
defers.length === 0 ? emptyList : [defers]
)
new Route(
method, path,
// Check for validator
args[0],
// Load the actions and alters
actions.length === 0 ? emptyList : [actions],
defers.length === 0 ? emptyList : [defers]
)
);

return this;
}

/**
* Create a validator
*/
static validate<const T extends ValidatorRecord>(validator: T) {
return validator;
}

/**
* Create a handler
*/
Expand Down Expand Up @@ -266,7 +247,6 @@ export type BaseByte = Byte<RoutesRecord, any>;
export * from './route';

export * from './types/handler';
export * from './types/validator';
export * from './types/responseInit';

// Internals and utils
Expand Down
43 changes: 4 additions & 39 deletions src/core/server/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { BaseRouter } from '@bit-js/blitz';

import type { DeferFn, Fn } from './types/handler';
import type { ValidatorRecord } from './types/validator';

import { getPropOfSetter, getPropOfState, isAsync, passChecks } from './utils/macro';

Expand All @@ -11,7 +10,6 @@ import { getPropOfSetter, getPropOfState, isAsync, passChecks } from './utils/ma
export class Route<
Method extends string,
Path extends string,
Validator extends ValidatorRecord<Path>,
Handler extends Fn<any>
> {
/**
Expand All @@ -20,7 +18,6 @@ export class Route<
constructor(
readonly method: Method,
readonly path: Path,
readonly validator: Validator,
readonly handler: Handler,
readonly actions: Fn[][],
readonly defers: DeferFn[][]
Expand All @@ -37,7 +34,7 @@ export class Route<
// Merge pathname
base.length === 1 ? path : (path.length === 1 ? base : base + path) as Path,
// Copy other props
this.validator, this.handler,
this.handler,
// Push other stuff
otherAppActions.length === 0 ? this.actions : [otherAppActions, ...this.actions],
otherAppDefers.length === 0 ? this.defers : [...this.defers, otherAppDefers]
Expand All @@ -59,19 +56,17 @@ export class Route<
*
*/
compile() {
const { handler, validator, actions, defers } = this;
const { handler, actions, defers } = this;

// Conditions
const noActions = actions.length === 0;
const noValidator = validator === null;
const noDefers = defers.length === 0;

if (noValidator && noActions && noDefers) return handler;
if (noActions && noDefers) return handler;

const keys = [];
const statements = [];
const values = [];
const paramsKeys = [];

let hasAsync = false;
let noContext = true;
Expand Down Expand Up @@ -118,36 +113,6 @@ export class Route<
}
}

// Compile validators and check result
if (!noValidator) {
for (const key in validator) {
// Validators
const fn = validator[key], fnKey = 'f' + idx;

keys.push(fnKey);
values.push(fn);

const fnAsync = isAsync(fn);
hasAsync = hasAsync || fnAsync;

const fnNoContext = fn.length === 0;
noContext = noContext && fnNoContext;

const result = `${fnAsync ? 'await ' : ''}${fnKey}(${noContext ? '' : 'c'})`;
if (passChecks(fn))
paramsKeys.push(`${key}:${result}`);
else {
paramsKeys.push(key);
statements.push(`const ${key}=${result};if(${key} instanceof Response)return ${key}`);
}

++idx;
}

// Set state
statements.push(`c.state={${paramsKeys.join()}}`);
}

// Restricted variable for the main handler
keys.push('$');
values.push(handler);
Expand Down Expand Up @@ -194,7 +159,7 @@ export class Route<
}
}

export type BaseRoute = Route<any, any, any, any>;
export type BaseRoute = Route<any, any, any>;

// Route list
export type RoutesRecord = BaseRoute[];
Expand Down
7 changes: 3 additions & 4 deletions src/core/server/types/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import { htmlPair, jsonPair, type BasicResponse, type JsonResponse, type Nullabl
import type { CommonHeaders, CommonResponseInit } from '../types/responseInit';

// Base context
export class Context<Params, State = undefined> implements CommonResponseInit {
state!: State;
export class Context<Params> implements CommonResponseInit {
status!: number;
headers: CommonHeaders;

Expand Down Expand Up @@ -65,10 +64,10 @@ export class Context<Params, State = undefined> implements CommonResponseInit {
}
};

export type BaseContext = Context<any, any>;
export type BaseContext = Context<any>;

// Basic handler and actions
export type BaseHandler<Path extends string, Set, State = undefined> = (c: Context<Params<Path>, State> & Set) => any;
export type BaseHandler<Path extends string, Set> = (c: Context<Params<Path>> & Set) => any;

export type Fn<T = any> = (c: BaseContext & T) => any;
export type DeferFn<T = any> = (c: BaseContext & T & { res: any }) => any;
15 changes: 0 additions & 15 deletions src/core/server/types/validator.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/plugins/server/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export type InferFormSchema<Schema extends FormSchema> = {

export const form = {
get<Options extends FormPropertyOptions>(prop: string, { type, multipleItems }: Options): (ctx: BaseContext) => Promise<InferFormPropertyOptions<Options> | null> {
return $async(Function(`const p=(f)=>${type === 'string'
return $async(Function('n', `const p=(f)=>${type === 'string'
? (multipleItems === true
? `{const v=f.getAll(${JSON.stringify(prop)});return v.every((x)=>typeof x==='string')?v:null;}`
: `{const v=f.get(${JSON.stringify(prop)});return typeof v==='string'?v:null;}`)
Expand All @@ -36,7 +36,7 @@ export const form = {
? `{const v=f.getAll(${JSON.stringify(prop)});return v.every((x)=>x instanceof File)?v:null;}`
: `{const v=f.get(${JSON.stringify(prop)});return v instanceof File?v:null;}`)
: `f.has(${JSON.stringify(prop)})`
};return (c)=>c.req.formData().then(p);`)())
};return (c)=>c.req.formData().then(p).catch(n);`)(noop))
},

schema<Schema extends FormSchema>(schema: Schema): (ctx: BaseContext) => Promise<InferFormSchema<Schema> | null> {
Expand Down

0 comments on commit 4fb6f15

Please sign in to comment.