Comments (5)
@piyush-nudge I think this is what you want.
import { Type } from "@sinclair/typebox";
import { Value } from "@sinclair/typebox/value";
export const request = Type.Object({
query: Type.Object({
pageState: Type.String({ default: "sample" }),
all: Type.String({ default: "false" })
}, { default: {} }),
limit: Type.Transform(Type.String({ default: "10" }))
.Decode(value => Number(value))
.Encode(value => value.toString())
});
const obj = { query: { all: "false" } };
Value.Default(request, obj);
console.log("default values:", obj);
const decoded = Value.Decode(request, obj);
console.log("decoded values:", decoded);
default values: { query: { all: 'false', pageState: 'sample' }, limit: '10' }
decoded values: { query: { all: 'false', pageState: 'sample' }, limit: 10 }
First, Value.Decode
does not mutate the parameters. You have to use the return value.
Second, it seems that it does not create default if the nested object does not have default value.
from typebox.
@joshuaavalon Hey, thanks for handling this one :) (that's super appreciated!)
@piyush-nudge will close up this issue for now, but if you have any follow up questions, feel free to ping on this thread.
Thanks all!
S
from typebox.
@piyush-nudge From my experience, Type.Optional(Type.String({ default: 'sample' }))
is setting the default value for Type.String()
not Type.Optional()
.
There is no way to set the default value for Type.Optional()
. But if you always use the default value, you can just remove the Type.Optional()
.
If you want to keep Type.Optional()
, you can set the default value on parent's default value instead.
export const request = Type.Object({
pageState: Type.Optional(Type.String()),
query: Type.Object({
all: Type.String({ default: 'false' }), // if false, return only parent tasks.
}),
limit: Type.Transform(Type.String({ default: '10' }))
.Decode(value => Number(value))
.Encode(value => value.toString())
}, { default: { pageState: 'sample' } });
from typebox.
@joshuaavalon Thanks for the clarification regarding Type.Optional()
and default values. However, if we want to use the pageState
inside the query object and wanted to use default values after removing the Type.Optional()
property frompageState
field, the value is still not as expected and throws an error when we try to use Value.Decode()
on the request object:
Snippet:
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
export const request = Type.Object({
query: Type.Object({
pageState: Type.String({ default: 'sample' }),
all: Type.String({ default: 'false' }),
}),
limit: Type.Transform(Type.String({ default: '10' }))
.Decode(value => Number(value))
.Encode(value => value.toString()),
});
const obj = {
query: {
all: 'false'
},
};
Value.Default(request, obj);
console.log("default values:", obj);
Value.Decode(request, obj);
console.log("decoded values:", obj);
Logs and errors:
default values: {
query: {
all: "false",
},
limit: "10",
}
1 | /** The base Error type thrown for all TypeBox exceptions */
2 | export class TypeBoxError extends Error {
3 | constructor(message) {
4 | super(message);
^
error: Unable to decode value as it does not match the expected schema
at new TypeBoxError (server\node_modules\@sinclair\typebox\build\esm\type\error\error.mjs:4:9)
at new TransformDecodeCheckError (server\node_modules\@sinclair\typebox\build\esm\value\transform\decode.mjs:24:9)
at Decode (server\node_modules\@sinclair\typebox\build\esm\value\value\value.mjs:42:15)
at server\test.ts:23:1
@sinclairzx81 Is it the expected behavior with Value.Default()
because when we are keeping pageState
in the top level of the request object, the default values are getting assigned correctly, but when we are adding another level of nesting (placing pageState
inside the query
object) the values are not getting assigned correctly. As you explained earlier, we can use a default object like this:
export const request = Type.Object({
query: Type.Object({
pageState: Type.String({ default: 'sample' }),
all: Type.String({ default: 'false' }),
}),
limit: Type.Transform(Type.String({ default: '10' }))
.Decode(value => Number(value))
.Encode(value => value.toString())
}, { default: { query: { pageState: 'sample' } }});
But we are having larger objects for type validations and if it's possible to use Value.Default()
with nested objects, it would be a life-saver, otherwise we have to assign whole default objects like the above snippet (I'm praying that there is some workaround to making Value.Default()
work)
from typebox.
Thanks @joshuaavalon, this method worked for our usecase and now we are getting all the correct default values for the nested objects. Thanks for the quick reply!
from typebox.
Related Issues (20)
- Max call stack size exceeded HOT 1
- Value.Convert() doesn't work with nullable record HOT 1
- Variadic Any Typed function parameters HOT 2
- How to do a cross field validation? HOT 3
- Undefined is incorrectly handled in Diff HOT 3
- QoL helper: `TypeCheck.Ensure` HOT 3
- Usage of `Type.Composite` with `Type.TemplateLiteral` HOT 3
- `Check` doesn't validate strings with enums HOT 4
- `Type.Omit` mixed with `Type.Union` is not preserving the `additionalProperties` attribute HOT 2
- Advice to compose types HOT 3
- Access to schema properties for non TObject schemas HOT 5
- Type.Optional with Type.Transform unexpected behaviour HOT 1
- ts(7056) when you try to export a big union type HOT 1
- `Value.Default` does not traverse object schema HOT 2
- Unable to use a union of literal as record key type after upgrading version HOT 2
- Unknown format 'email' after update HOT 3
- Uncaught Error: Cannot access 'Object' before initialization HOT 3
- Support for conditional optional based on other value HOT 3
- Type.Mapped does not handle optional properties the same as Typescript HOT 2
- Add changelog or create a new release for each tag HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from typebox.