serverless-models-plugin
serverless-models-plugin copied to clipboard
How to retrieve models/schemas in Lambda/Javascript?
Since API Gateway does not use Models to perform any schema validation of request/response messages (currently at least), Im considering using one of the Javascript JSON-Schema validator implementations for NodeJS to do this myself inside Lambda handler.
In order to do that, validators are requiring schemas and then I need to be able to retrieve the models/schemas from s-models.json file. Is it as easy as just using require() function, or do you suggest another way?
For the current version of the models plugin and Serverless this approach should work for your special use case although it is not universal as you can define your models as s-models.json or s-models.yaml.
In future this could even be part of the plugin itself, so that it could generate a validator function/class or provide a way to retrieve the model definitions at runtime. But as I need to do excessive changes for the upcoming Serverless V1, this will not happen in this version. I will try to keep the model file location the same for Serverless V1 but as things are not yet finalized there, it might still change.
In my case I use only json, so it is quite easy to load the models.
In regards providing validate function as part of the plugin. That depends of what scope this plugin will have in future. So far it is isolated for deploying models to API Gateway, which it does greatly. Doing validations as well would extend its current scope.
Off topic: when is serverless v1 release planned?
Exactly. They are already working on the new version, but I do not know any date when it will be released,
New obstacle, s-models.json is placed in the root of my project, but Im putting all function code within /function folder, which is also the one being deployed to AWS. This means that I do not have access to s-models.json in function handler when deployed to AWS since it is not bundled within the .zip file. I know I can modify handler path in s-function.json to include all files in the project, but that will increase the total file size.
Is it possible to retrieve models in other way, within the function handler?
Currently not. As a hack you might symlink the s-models.json into your function root.
Could you please be more specific?
Like this
+ s-project.json
+ s-models.json
+ function
+ node_modules
+ s-models.json (symlink to ../s-models.json)
Aah. Thanks. But really an hack, specially when commiting to GIT.
Yes it is :-) But at least GIT handles symlinks correctly.