apigee-127 / sway Goto Github PK
View Code? Open in Web Editor NEWA library that simplifies OpenAPI (fka Swagger) integrations/tooling.
License: MIT License
A library that simplifies OpenAPI (fka Swagger) integrations/tooling.
License: MIT License
Operation#validateRequest
takes a single object
argument and documents what properties within the structure are used for validation. Operation#validateResponse
does not follow this approach, for good reason. (There is no consistent way to describe a response across different Node.js environments while most, if not all, provide raw access to the http.IncomingMessage
.) It would be nice if we could make both APIs work the same, if possible.
It simpler to provide code sample:
var swagger = {
"definitions": {
"TestSchema": {
"properties": {
"default": {
},
"id": {
},
},
},
},
"info": {
"title": "Test sample",
"version": "v1.0"
},
"paths": {},
"swagger": "2.0"
};
sway.create({definition: swagger})
.then(function (swaggerObj) {
var result = swaggerObj.validate();
console.log('works ' + JSON.stringify(swaggerObj.getLastErrors()));
})
.catch(function (error) {
console.log('error ' + error);
});
and it crash: TypeError: undefined is not a function
I already fix this issue and will make PR
Until we have a way to allow the user to alter object attributes at runtime, we should make it explicitly clear that these created objects are read-only by using Object.freeze
.
To make it where you don't have to use Gulp to run tests, we should serve the necessary files from Karma's server instead of the HTTP server we spin up in the Gulp file.
var swagger = {
"swagger": "2.0",
"info": {
"version": "0.9",
"title": "test API"
},
"definitions": {
"ContactList": {
"properties": {
"customfields": {
"$ref": "ContactCustomFieldSchema"
}
}
},
"ContactListUpdate": {
"properties": {
"customfields": {
"$ref": "ContactCustomFieldSchema"
}
}
}
},
"paths": {}
};
var sway = require('./index.js')
sway.create({definition: swagger})
.then(function (swaggerObj) {
var result = swaggerObj.validate();
console.log(JSON.stringify(swaggerObj.getLastErrors(), null, 2));
});
This code produce following output:
[
{
"code": "OBJECT_ADDITIONAL_PROPERTIES",
"message": "Additional properties not allowed: paths,definitions,info,swagger",
"path": [
"definitions",
"ContactListUpdate",
"properties",
"customfields"
],
"description": "A deterministic version of a JSON Schema object."
}
]
Now that we have response validation, we have a few response-specific APIs.
See below. The _.isPlainObject check in types.js fails on a standard request object.
Parameter.prototype.getValue = function (req) {
if (_.isUndefined(req)) {
throw new TypeError('req is required');
} else if (!_.isPlainObject(req)) {
throw new TypeError('req must be an object');
} else if (validParameterLocations.indexOf(this.in) === -1) {
throw new Error('Invalid \'in\' value: ' + this.in);
}
I want to switch from swagger-tools
to sway
.
What's blocking me is absence of CLI tool which I can you inside build scripts.
Is it planned feature?
I was debugging a validation problem with my swagger specification, and while doing so, I tried to validate the PetStore example in http://editor.swagger.io/.
That gave me a similar error to the one I was trying to solve:
Path parameter is declared but is not defined: petId
Could there be a problem with validators.js? (I did not investigate yet)
We need a few new APIs:
Operation#getParameter(location, name)
Operation#getParametersByLocation(location)
Operation#getParametersByName(name)
The last two might not be required but I could see someone wanting them.
There are three parts to this:
options.loaderOptions
to options.jsonRefs
, we forgot to change all referencesoptions.jsonRefs.location
based on the location used in options.definition
I neglected these tests because json-refs was so heavily tested but this has come back to bite me in the tail.
Add a getter to ParameterValue
to do validation.
Apparently descriminator
is something that has been added to json schema in swagger.
Please support it in sway as well.
For context please go to:
swagger-api/swagger-editor#765
Added a parameter:
- name: example_file
in: formData
description: An example file
required: true
type: file
Provided the example_file data in req.files['example_file']. Got this error from Sway when processing:
[TypeError: Invalid 'type' value: file]
Tried adding "type" to the validTypes array in types.js. Then get this error from Sway:
{ [Error: Value failed JSON Schema validation]
code: 'SCHEMA_VALIDATION_FAILED',
errors:
[ { code: 'KEYWORD_TYPE_EXPECTED',
message: 'Keyword \'type\' is expected to be of type \'array,boolean,integer,number,null,object,string\'',
path: [] } ],
failedValidation: true,
path: [ 'paths', '/hello_file', 'get', 'parameters', '1' ] }
Right now we take options and use them to drive other libraries, like json-refs. We should encapsulate them to save API consumers.
When doing type conversion for strings when the expected type is object
and the string contains a JSON encoded object, it is not converted to object.
This breaks response validation in swagger-restify, which sets up connect middleware, which passes the body of the response to the validator as a string: https://github.com/theganyo/swagger-node-runner/blob/master/lib/connect_middleware.js#L162. I can't see what else it can do, and it would have worked before 473c6db.
If you have a model A
that has a property that references itself, when model B
inherits from A
it validates with an error like Schema object inherits from itself: #/definitions/A
wrongly.
Following is valid Swagger:
{
"info": {
"title": "test",
"version": "1.0.0",
},
"paths": {
"/{arg1}": {
"get": {
"parameters": [
{
"name": "arg1",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": { "description": "OK" }
}
}
},
"/{arg2}": {
"head": {
"parameters": [
{
"name": "arg2",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": { "description": "OK" }
}
}
}
},
"swagger": "2.0"
}
But currently it throws an error:
[
{
"code": "EQUIVALENT_PATH",
"message": "Equivalent path already exists: /{arg2}",
"path": [
"paths",
"/{arg2}"
]
}
]
P.S. I have PR, but I submit issues just to mark it properly in tests.
Hi,
On line 98 in parameter-value.js, there is a condition about which cases we do not want to do schema validation.
The last condition is
// * The schema is for a string type with date/date-time format and the value is a date
&&
(schema.type !== 'string' && !_.isDate(value)))
So when I have a parameter like
parameters:
- in: formData
name: someField
description: some description
required: true
type: string
format: email
Email format validation is not performed on this field. When I removed that condition, there is email validation. I would like to ask, whether, in situations where we have string field and format not date, we should do schema validation? Or am I missing something?
Originally reported here: apigee-127/swagger-tools#241
We need to use the @module
and @alias
jsdoc tags to generate better API documentation.
spec:
swagger: '2.0'
info:
version: 0.0.0
title: Simple API
paths:
/:
parameters:
- name: parameter_name
in: path
required: true
description: description
type: string
get:
responses:
'200':
description: OK
Error:
Swagger Error
Path parameter is defined but is not declared: parameter_name
Details
Object
code: "MISSING_PATH_PARAMETER_DECLARATION"
message: "Path parameter is defined but is not declared: parameter_name"
path: Array [1]
0: "0"
part of swagger:
definitions:
$ref: ./definitions/index.yaml
jsonRefs.location value:
"http://localhost:9000/#/"
Request is made to:
http://localhost:9000//definitions/index.yaml
I realize that api.definition
and api.resolved
provide the root document and the fully resolve document but it would be nice to have APIs for these (for simplicity) and to also have an way to get a Swagger document that isn't fully resolved but instead has all of its remote references resolved. We almost got this when working on #43 but I canned #43 due to it adding a lot of complexity for little/no gain.
swagger: '2.0'
info:
version: 0.0.0
title: Simple API
paths:
/:
get: null
Uncaught (in promise) TypeError: Cannot read property 'parameters' of null
at http://localhost:9000/bower_components/sway/browser/sway.js:1682:24
getOperation is great, but would love a way to grab all operations by tag. I don't have tons of JS experience, but may try to make the PR myself. Would love this functionality though.
While Swagger allows you to have a schema without a type
parameter, this is typically a mistake. We should create a warning for this.
We need to validate the readOnly
field: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields-13
Hey, sorry to bother, but it seems that the npm module is out of date with the library here. It would be quite helpful if we could have those brought together again. Thanks!
Because of all prototype and circular refs it's impossible to get the raw Swagger JSON with no additions. ..or I don't know how to get it?
Right now the format generators/validators are just there to make z-schema/json-schema-faker happy but they are untested. We should remedy this.
The plugin architecture was a way to have pluggable Swagger support. I think the simplest way to do this would be to instead of having plugins, have a way to pre-process Swagger documents prior to processing the object model from them. This should make the internal code much simpler to read and should make it so that supporting other versions of Swagger could be done simpler as well.
sway will currently treat the body
parameter for Operation#validateResponse
as an object
and fails validation.
We need to update z-schema to 3.13.0
so that we can avoid treating unknown formats as validation errors.
Originally reported at swagger-api/swagger-editor#612
The current browser builds of swagger-core-api are huge and we should investigate if we can fix this. Here is a useful link: https://gist.github.com/whitlockjc/28b49ddc7558adbea77b Also, I did some preliminary looking and it seems json-schema-faker uses faker.js and is including all of its locales, something that should be avoided.
The validation API has drifted since it was originally written and needs to be updated. We need to document the return type for the validator callback and what the structure of the error/warning object.
A GET operation should not have body or formData parameter. Throw a validation error if there was one.
/cc @webron
When we load a Swagger document, we will fully dereference all references in the document. For simple files, this is fine. For files with a lot of nested objects and such, this can be a performance bottle neck. It would be nice if Sway only resolved the remote references and then could resolve relative references on an as needed basis, preferably with some sort of cache to avoid having to reprocess references more than once. Since JsonRefs#resolveRefs
is always async, this would mean having to change our APIs to be async or we will need to update json-refs
to have a synchronous API that only works on local references.
{ [Error: Value failed JSON Schema validation]
code: 'SCHEMA_VALIDATION_FAILED',
errors:
[ { code: 'INVALID_TYPE',
message: 'Expected type string but found type undefined',
path: [],
description: 'The name of the person to whom to say hello' } ],
failedValidation: true,
path: [ 'paths', '/hello', 'get', 'parameters', '0' ] }
during autocomplete in Swagger Editor user might type invalid values for $ref
. Instead of throwing an error, return an error in the callback.
When doing type conversion for strings when the expected type is object
we have a bug where the provided value will fail. Here is an example:
> var x = "Jeremy";
undefined
> JSON.parse(x)
SyntaxError: Unexpected token J
at Object.parse (native)
at repl:1:6
at REPLServer.defaultEval (repl.js:248:27)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.<anonymous> (repl.js:412:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:210:10)
at REPLServer.Interface._line (readline.js:549:8)
> x = JSON.stringify(x);
'"Jeremy"'
> x
'"Jeremy"'
> JSON.parse(x)
'Jeremy'
The reason this matters is raw string values will likely fail to convert due to a runtime issue, as shown above, instead of a type checking failure later when doing type checks.
When allowEmptyValue
is set to true
, an empty value is a valid value and should not cause any parameter validation failures.
Originally reported here: apigee-127/swagger-tools#282
Wrapping callbacks in Promises is confusing and since we've removed callback-support for the other libraries related to sway (json-refs and path-loader), we should do the same here.
Imagine you need to do some preprocessing to your Swagger document prior to being processed into a SwaggerApi
model. You cannot do that right now and we should provide facilities for this.
Right now, we will always generate a mock/sample value from the operation response's JSON Schema whenever you call Operation#getResponseSample
. It would be nice to either update that API or add a new API to get the example value when available.
swagger-tools/issues/294 pointed out that qs style object processing is not working as expected. While sway does not get involved in the backend parsing of query parameters, we should at least be aware that qs could be involved and support it.
From swagger-api/swagger-editor#611
A simpler YAML to reproduce:
---
swagger: '2.0'
info:
version: 0.0.0
title: Simple API
paths:
/:
$ref: 'http://localhost:9000/root.json'
Inside root.json
:
{
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
}
After calling SwaggerApi#create
the api.definition
value is:
{
"swagger": "2.0",
"info": {
"version": "0.0.0",
"title": "Simple API"
},
"paths": {
"/": {
"$ref": "http://localhost:9000/root.json"
}
}
}
Take this path as an example: /{}
Currently error thrown is: "Path parameter is declared but is not defined:"
There are a number of places in the Swagger JSON Schema file where oneOf
is used (parameters for example) and when the JSON Schema validator produces its error, it is some cryptic error like this: Data does not match any schemas from 'oneOf'
. This was also reported in apigee-127/swagger-tools#200 What we need to do is special-case these situations to produce a better, human readable error instead of just providing the error from our JSON Schema validator (https://github.com/zaggino/z-schema)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.