Replies: 1 comment 2 replies
-
I keep answering my own questions 😆 After digging through the source code a bit, I was able to create a custom In case anyone is interested in the code: import {
$visibility,
type DecoratorContext,
type Model,
type ModelProperty,
validateDecoratorTarget,
} from '@typespec/compiler';
function updateModelPropertiesInPlace(
model: Model,
callback: (key: string, prop: ModelProperty) => ModelProperty,
) {
for (const [key, prop] of model.properties) {
const updatedProp = callback(key, prop);
model.properties.set(key, updatedProp);
}
}
export const $withPartial = (
context: DecoratorContext,
target: Model,
): void => {
if (!validateDecoratorTarget(context, target, '@withPartial', 'Model')) {
return;
}
updateModelPropertiesInPlace(target, (key, prop) => {
if (prop.optional) return prop;
return { ...prop, optional: true };
});
};
export const $withSetVisibility = (
context: DecoratorContext,
target: Model,
...visibilities: string[]
): void => {
if (
!validateDecoratorTarget(context, target, '@withSetVisibility', 'Model')
) {
return;
}
updateModelPropertiesInPlace(target, (key, prop) => {
return {
...prop,
decorators: [
...prop.decorators.filter((d) => d.decorator !== $visibility),
{
decorator: $visibility,
args: visibilities.map((visibility) => ({
value: context.program.checker.createLiteralType(visibility),
jsValue: visibility,
})),
},
],
};
});
for (const [key, prop] of target.properties) {
$visibility(context, prop, ...visibilities);
}
}; and the
|
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm creating a REST interface and want to re-use a model in a different place but change all of its properties to being optional and read-only. For example, having a
Partial<Foo>
data type would allow to making all properties optional for use in aPATCH
HTTP request. Making all properties of a model read-only (setting their visibility to "read") would also be helpful to have more flexibility in API design without redefining the model.What I'm looking for are two data types (and possible variations):
Partial<Model>
should make all properties ofModel
optional. In some cases aPartialDeep<Model>
might be useful as well.ReadOnly<Model>
,Visibility<Model, "read">
and/or aDefaultVisibility<Model, "read">
to overwrite the visibility of all propertiesIs it possible to build a custom TypeSpec library to add these features or would this need to be added in the core?
Beta Was this translation helpful? Give feedback.
All reactions