|
6 | 6 | TArray,
|
7 | 7 | TDate,
|
8 | 8 | TUnsafe,
|
9 |
| - TypeRegistry |
| 9 | + TypeRegistry, |
| 10 | + TInteger |
10 | 11 | } from '@sinclair/typebox'
|
11 | 12 | import { TypeSystem } from '@sinclair/typebox/system'
|
12 | 13 | import {
|
@@ -261,6 +262,12 @@ const Files: ElysiaFiles =
|
261 | 262 | if (!FormatRegistry.Has('numeric'))
|
262 | 263 | FormatRegistry.Set('numeric', (value) => !!value && !isNaN(+value))
|
263 | 264 |
|
| 265 | +if (!FormatRegistry.Has('integer')) |
| 266 | + FormatRegistry.Set( |
| 267 | + 'integer', |
| 268 | + (value) => !!value && !isNaN(+value) && Number.isInteger(+value) |
| 269 | + ) |
| 270 | + |
264 | 271 | if (!FormatRegistry.Has('boolean'))
|
265 | 272 | FormatRegistry.Set(
|
266 | 273 | 'boolean',
|
@@ -354,6 +361,33 @@ export const ElysiaType = {
|
354 | 361 | })
|
355 | 362 | .Encode((value) => value) as any as TNumber
|
356 | 363 | },
|
| 364 | + Integer: (property?: NumberOptions): TInteger => { |
| 365 | + const schema = Type.Integer(property) |
| 366 | + |
| 367 | + return t |
| 368 | + .Transform( |
| 369 | + t.Union( |
| 370 | + [ |
| 371 | + t.String({ |
| 372 | + format: 'integer', |
| 373 | + default: 0 |
| 374 | + }), |
| 375 | + t.Number(property) |
| 376 | + ], |
| 377 | + property |
| 378 | + ) |
| 379 | + ) |
| 380 | + .Decode((value) => { |
| 381 | + const number = +value |
| 382 | + if (isNaN(number)) return value |
| 383 | + |
| 384 | + if (!Value.Check(schema, number)) |
| 385 | + throw new ValidationError('property', schema, number) |
| 386 | + |
| 387 | + return number |
| 388 | + }) |
| 389 | + .Encode((value) => value) as any as TInteger |
| 390 | + }, |
357 | 391 | Date: (property?: DateOptions) => {
|
358 | 392 | const schema = Type.Date(property)
|
359 | 393 |
|
@@ -637,6 +671,7 @@ declare module '@sinclair/typebox' {
|
637 | 671 | ObjectString: typeof ElysiaType.ObjectString
|
638 | 672 | ArrayString: typeof ElysiaType.ArrayString
|
639 | 673 | Numeric: typeof ElysiaType.Numeric
|
| 674 | + Integer: typeof ElysiaType.Integer |
640 | 675 | File: typeof ElysiaType.File
|
641 | 676 | Files: typeof ElysiaType.Files
|
642 | 677 | Nullable: typeof ElysiaType.Nullable
|
@@ -675,6 +710,7 @@ t.ArrayString = ElysiaType.ArrayString
|
675 | 710 | * Will be parse to Number
|
676 | 711 | */
|
677 | 712 | t.Numeric = ElysiaType.Numeric
|
| 713 | +t.Integer = ElysiaType.Integer |
678 | 714 |
|
679 | 715 | t.File = (arg = {}) =>
|
680 | 716 | ElysiaType.File({
|
|
0 commit comments