-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
136 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import { $async, type BaseContext } from "../../core"; | ||
import { noop } from "../../utils/defaultOptions"; | ||
|
||
interface TypeMap { | ||
string: string; | ||
number: number; | ||
bool: boolean; | ||
file: File; | ||
} | ||
|
||
export interface FormPropertyOptions { | ||
type: keyof TypeMap; | ||
multipleItems?: boolean; | ||
} | ||
export type InferFormPropertyOptions<T extends FormPropertyOptions> = | ||
T['multipleItems'] extends true ? (TypeMap[T['type']])[] : TypeMap[T['type']]; | ||
|
||
export type FormSchema = Record<string, FormPropertyOptions>; | ||
|
||
export type InferFormSchema<Schema extends FormSchema> = { | ||
[K in keyof Schema]: InferFormPropertyOptions<Schema[K]> | ||
} | ||
|
||
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' | ||
? (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;}`) | ||
: type === 'number' | ||
? (multipleItems === true | ||
? `{const v=f.getAll(${JSON.stringify(prop)}).map((t)=>+t);return v.some(Number.isNaN)?v:null;}` | ||
: `{const v=+f.get(${JSON.stringify(prop)});return Number.isNaN(v)?null:v;}`) | ||
: type === 'file' | ||
? (multipleItems === true | ||
? `{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);`)()) | ||
}, | ||
|
||
schema<Schema extends FormSchema>(schema: Schema): (ctx: BaseContext) => Promise<InferFormSchema<Schema> | null> { | ||
const parts: string[] = [''], sets = []; | ||
|
||
for (const key in schema) { | ||
const item = schema[key]; | ||
const { type } = item; | ||
|
||
if (type === 'string') { | ||
parts.push(item.multipleItems === true | ||
? `const ${key}=f.getAll(${JSON.stringify(key)});if(${key}.some((x)=>typeof x!=='string'))return null;` | ||
: `const ${key}=f.get(${JSON.stringify(key)});if(typeof ${key}!=='string')return null;` | ||
); | ||
sets.push(key); | ||
} else if (type === 'number') { | ||
parts.push(item.multipleItems === true | ||
? `const ${key}=f.getAll(${JSON.stringify(key)}).map((t)=>+t);if(${key}.some(Number.isNaN))return null;` | ||
: `const ${key}=+f.get(${JSON.stringify(key)});if(Number.isNaN(${key}))return null;` | ||
); | ||
sets.push(key); | ||
} else if (type === 'file') { | ||
parts.push(item.multipleItems === true | ||
? `const ${key}=f.getAll(${JSON.stringify(key)});if(${key}.some((x)=>!(x instanceof File)))return null;` | ||
: `const ${key}=+f.get(${JSON.stringify(key)});if(!(${key} instanceof File))return null;` | ||
); | ||
} else | ||
sets.push(`${key}:f.has(${JSON.stringify(key)})`); | ||
} | ||
|
||
return $async(Function('n', `const p=(f)=>{${parts.join('')}return {${sets}};};return (c)=>c.req.formData().then(p).catch(n);`)(noop)); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import { form, Context } from '@bit-js/byte'; | ||
import { expect, test } from 'bun:test'; | ||
|
||
function context(obj: Record<string, any>) { | ||
const body = new FormData(); | ||
|
||
for (const key in obj) { | ||
const value = obj[key]; | ||
|
||
if (Array.isArray(value)) { | ||
for (let i = 0, { length } = value; i < length; ++i) { | ||
const item = value[i]; | ||
|
||
body.append(key, typeof item === 'string' || item instanceof File ? item : item + ''); | ||
} | ||
} else if (typeof value === 'boolean') { | ||
if (value) | ||
body.append(key, ''); | ||
} else body.append(key, typeof value === 'string' || value instanceof File ? value : value + ''); | ||
} | ||
|
||
return new Context(new Request('http://localhost:3000', { | ||
method: 'POST', body | ||
})) | ||
} | ||
|
||
test('Form getters', async () => { | ||
const parseStr = form.get('name', { type: 'string' }); | ||
expect(await parseStr(context({ name: 'a' }))).toBe('a'); | ||
expect(await parseStr(context({ age: 16 }))).toBe(null); | ||
|
||
const parseNum = form.get('id', { type: 'number' }); | ||
expect(await parseNum(context({ id: 0 }))).toBe(0); | ||
expect(await parseNum(context({ id: 'str' }))).toBe(null); | ||
|
||
|
||
const parseBool = form.get('darkMode', { type: 'bool' }); | ||
expect(await parseBool(context({ darkMode: '' }))).toBe(true); | ||
expect(await parseBool(context({ other: '' }))).toBe(false); | ||
}); | ||
|
||
test('Form schema', async () => { | ||
const parseForm = form.schema({ | ||
name: { type: 'string' }, | ||
age: { type: 'number' }, | ||
darkMode: { type: 'bool' }, | ||
ids: { type: 'number', multipleItems: true } | ||
}); | ||
|
||
const o1 = { | ||
name: 'dave', | ||
age: 18, | ||
darkMode: true, | ||
ids: [5, 6] | ||
}; | ||
expect(await parseForm(context(o1))).toEqual(o1); | ||
}); |