I have been working on a library that integrates an OpenAPI definition with a REST API definition on the CDK. This is the second blog post of the series that will walk you through the development of the library.
In the first blog post of this series, we left the following challenge,
How can we achieve compatibility with
Since it is too hard not to reuse
RestApi, I am going to write a subclass for it.
Before extending the AWS Cloud Development Kit (CDK) API, let us define minimal interfaces. Please note that I have excerpted and modified the interfaces and code shown in the following sections from my library for simplicity. You can find their full definitions in my GitHub repository.
IRestApiWithSpec is the extension of
IResourceWithSpec is the extension of
* To correctly extend
IResourceWithSpec has to implement
Resource rather than
On the other hand,
IRestApiWithSpec.root has to implement
IResource instead of
Resource, so the definition
root: IResourceWithSpec in
IRestApiWithSpec is too specific.
However, it should not matter because the public interface of
IResource are the same as far as I know.
ResourceOptionsWithSpec is the extension of
MethodOptionsWithSpec is the extension of
But this attempt has failed because it would make
MethodOptionsWithSpec unassignable to
So I have introduced a new property
requestParameterSchemas as a workaround.
I omit the details of
RestApiWithSpecProps for simplicity.
Please refer to my GitHub repository if you are interested in it.
Here, the question is how to implement
root of the superclass (
RestApi) sounds good.
So how do we wrap it?
Write a wrapper class that just forwards most requests to
That will involve a lot of boilerplate.
Proxy should better meet our needs.
root is fairly easy.
All you have to do is implement the
get function of a handler object.
// root: IResource ;
Unfortunately, TypeScript does not recognize the proxied object as
IResourceWithSpec in the above code and ends up with an error.
Because the default TypeScript definition of the
Proxy constructor is something like the following,
To address this issue, we can extend the definition of the
Proxy constructor so that it can produce a type different from that of
This StackOverflow post exactly answers it.
So adding the following declaration solves the TypeScript error.
Every time we create a
Resource, we have to wrap it with a
Proxy as described in the section "Proxying root."
So I have introduced a factory method
augmentResource that can wrap any existing
IResource with the features of
This factory method can also be applied to
The above code has been simplified; you can find the actual definition in my GitHub repository.
In this blog post, I have introduced
Proxy to facilitate the extension of the CDK API.
I also have shown a trick to circumvent a TypeScript error about
In an upcoming blog post, we will tackle the challenge of when we should output an OpenAPI definition file.
TypeScript bindings of the OpenAPI 3 specification itself.