I am having a problem with setting up the swagger into my node.js application. I am using swagger-jsdoc and swagger-ui-express for creating documentation. Here are the versions
"swagger-jsdoc": "3.5.0", "swagger-ui-express": "4.1.3"
Below is the configs, which I pass to swagger-jsdoc.
openapi: 3.0.0
info:
description: test
version: 3.0.0
title: U-CRM api documentation
termsOfService: http://swagger.io/terms/
servers:
- url: 'https://localhost:5000'
description: Local server
tags:
- name: U-CRM
description: CRM for university
components:
parameters:
$ref: 'components/parameters/index.yml'
schemas:
$ref: 'components/schemas/index.yml'
paths:
$ref: '#/paths/index.yml'
After all, I get an error
Cannot read property 'parameters' of undefined
Actually, it is surprising to me, as I read swagger docs carefully.
What could be the problem?
OpenAPI does not support $ref everywhere. $ref can only be used in specific places where the OpenAPI Specification explicitly states that the value of a field can be a "Reference Object".
For example, $ref is not allowed directly under paths, under components/parameters and components/schemas - you can only reference individual paths, parameters and schemas.
The correct version of your example is:
paths:
/foo:
$ref: '#/paths/index.yml#/~1foo' # $ref to root node `/foo` in `paths/index.yml`
/bar:
$ref: '#/paths/index.yml#/~1bar' # $ref to root node `/bar` in `paths/index.yml`
components:
parameters:
param1:
$ref: 'components/parameters/index.yml#/param1'
param2:
$ref: 'components/parameters/index.yml#/param2'
schemas:
schema1:
$ref: 'components/schemas/index.yml#/schema1'
schema2:
$ref: 'components/schemas/index.yml#/schema2'
If you want to use $ref in random places, you'll have to pre-process your definition using a parser/tool that can resolve arbitrary $refs; this will give you a valid OpenAPI file that can be used with OpenAPI-compliant tools. One such pre-processing tool is json-refs, you can find an example of pre-processing here.
Related
I am having an issue while creating AWS::Appsync:Resolver Cloudformation in Serverless Framework using Javascript resolver.
My Javascript Resolver code in root dir /src/resolvers/jsResolver.js which I have attached to AWS::AppSync::Resolver cloudformation in code block. I have also installed npm plugin for appsync utils in my package.json
import { util } from '#aws-appsync/utils';
export function request(ctx) {
const {source, args} = ctx
return {
operation: 'Invoke',
payload: { field: ctx, arguments: args, source },
};
}
export function response(ctx) {
util.error("Failed to fetch relatedPosts", "LambdaFailure", ctx.prev.result)
return ctx.result;
}
My AWS::AppSync::Resolver Cloudformation is below in YML file also I have used Code as its Mandatory if I have declared it as APPSYNC_JS Runtime
AppSyncJsResolver:
Type: AWS::AppSync::Resolver
Properties:
ApiId: !GettAtt Graphql.APiId
Kind: PIPELINE
Code: ./src/resolvers/jsResolver.js <—- Here my code is breaking up with error contains one or more error
TypeName: Query
FieldName: getInfo
Runtime:
Name: APPSYNC_JS
RuntimeVersion: 1.0.0
PipelineConfig:
Functions:
- !GetAtt AppSyncFunction.FunctionId
I have tried above code as per AWS Cloudformation documentation for Appsync available where they have mentioned that in AWS::AppSync::Resolver for creating Javascript Resolver using Cloudformation as below one of the properties. which I have included in my AWS::AppSync::Resolver
Code
The resolver code that contains the request and response functions. When code is
used, the runtime is required. The runtime value must be APPSYNC_JS.
Required: No
Type: String
Required: No
Type: String
So I've tried this and cant find enough solutions regarding Javascript Resolvers all are available with VTL template specific.
With above code my CloudFormation build failed with the following error: An error occurred: AppSyncJSResolver- The code contains one or more errors. (Service: AWSAppSync; Status Code: 400; Error Code: BadRequestException; Request ID: 0245d64d-...; Proxy: null)
AppSyncJSResolver- which is my AWS::AppSync::Resolver in above code. and I have code property in that which giving me an error. I have verified with multiple sources and I am not finding any errors with my Javascript Resolver file /src/resolvers/jsResolver.js which I have declared in AppSyncJSResolver AWS::AppSync::Resolver in code property, I am not sure why I’m getting this error, any help would be great.
To answering my own question, The way I resolve it via two ways.
1. We can write whole Resolver code in YML Cloudformation in Code property like below. Make sure your resolver code should be inside of your Code property and use "|" special character (Multi-line code) after Code property.
AppSyncJsResolver:
Type: AWS::AppSync::Resolver
Properties:
ApiId: !GettAtt Graphql.APiId
Kind: PIPELINE
Code: |
import { util } from '#aws-appsync/utils';
export function request(ctx) {
const {source, args} = ctx
return {
operation: 'Invoke',
payload: { field: ctx, arguments: args, source },
};
}
export function response(ctx) {
util.error("Failed to fetch relatedPosts", "LambdaFailure",ctx.prev.result)
return ctx.result;
}
TypeName: Query
FieldName: getInfo
Runtime:
Name: APPSYNC_JS
RuntimeVersion: 1.0.0
PipelineConfig:
Functions:
- !GetAtt AppSyncFunction.FunctionId
2. If you want to keep your business logic out of YML file and keep it separate then you can use CodeS3Location property in your javascript resolver like below.
first create bucket in S3 and store your javascript resolver file with your resolver code in bucket. make sure you give enough IAM permission to your appsync to access your S3 bucket.
After above step you can rewrite your YML Cloudformation like below
AppSyncJsResolver:
Type: AWS::AppSync::Resolver
Properties:
ApiId: !GettAtt Graphql.APiId
Kind: PIPELINE
CodeS3Location:s3://my-bucket-name/my-filename.js
TypeName: Query
FieldName: getInfo
Runtime:
Name: APPSYNC_JS
RuntimeVersion: 1.0.0
PipelineConfig:
Functions:
- !GetAtt AppSyncFunction.FunctionId
Hope this help others and will contribute more about Javascript Resolver so it will be easier for other to find more complex solutions and get as much as resources about Javascript Resolver. Thanks to #Graham Hesketh for your suggestions.
i'm trying to use a plugin in my vuejs project that allows me to create projects in VUE within CMS October, however i updated my node and i believe i updated the webpack version too (from what i've researched) and now my plugin is not working for that error is occurring right on that line of code.
The properties of disableHostCheck and public no longer exist, I would like to know which one I could replace that would have the same effect?
I've been searching the webpack documentation and I couldn't understand which one would be equivalent.
// configure the dev server and public path based on environment
options.devServer = {
disableHostCheck: true,
public: 'http://localhost:8080',
};
ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'public'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
In webpack 5 is changed, please check:
devServer: {
allowedHosts: 'all',
}
I am trying to run my swagger file and i keep getting this error.
Error: ptr must be a JSON Pointer
at pathFromPtr (/Users/salma/Desktop/swaggerIntegration/node_modules/json-refs/index.js:1128:11)
at /Users/salma/Desktop/swaggerIntegration/node_modules/json-refs/index.js:293:45
at process.runNextTicks [as _tickCallback] (internal/process/next_tick.js:47:5)
at Function.Module.runMain (internal/modules/cjs/loader.js:800:11)
at executeUserCode (internal/bootstrap/node.js:526:15)
at startMainThreadExecution (internal/bootstrap/node.js:439:3)
and here is my swagger file
swagger: "2.0"
info:
version: "0.0.1"
title: employees DB
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths
basePath: /
#
schemes:
# tip: remove http to make production-grade
- http
- https
# format of bodies a client can send (Content-Type)
consumes:
- application/json
# format of the responses to the client (Accepts)
produces:
- application/json
paths:
/employees:
# binds a127 app logic to a route
x-swagger-router-controller: employees
get:
description: Returns 'Hello' to the caller
# used as the method name of the controller
operationId: index
parameters:
- name: name
in: query
description: The name of the person to whom to say hello
required: false
type: string
responses:
"200":
description: Success
schema:
# a pointer to a definition
$ref: "#/definitions/employeesListBody"
# responses may fall through to errors
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
/swagger:
x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
employeesListBody:
required:
- employees
properties:
employees:
type: array
items:
$ref: "#definitions/Employee"
Employee:
required:
- name
- email
- position
properties:
name:
type: string
email:
type: string
position:
type: string
age:
type: integer
minimum: 20
ErrorResponse:
required:
- message
properties:
message:
type: string
any idea how to solve that ?
is there an easier way to prettify the swagger file? because i get many parsing erros.
also does any one have a good example of using swagger with express and mongodb ?
many thanks.
One of the references is missing a / after #:
$ref: "#definitions/Employee"
Change it to:
$ref: "#/definitions/Employee"
# ^
If you paste your definition into http://editor.swagger.io, it shows where exactly the error is.
REST Api services is available in Node.js express app along with routes are specified properly. I am planning to use node.js to auto generate the swagger YAML Open API specification. Writing a swagger YAML manually is tough if you have more endpoints and the intention to add more endpoints will need to update everywhere.
Example: Consider a REST API services contains two basic endpoints and specified in the following YAML
swagger: "2.0"
info:
version: "0.0.1"
title: Hello World App
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths
basePath: /
#
schemes:
# tip: remove http to make production-grade
- http
- https
# format of bodies a client can send (Content-Type)
consumes:
- application/json
# format of the responses to the client (Accepts)
produces:
- application/json
paths:
/hello:
# binds a127 app logic to a route
x-swagger-router-controller: hello_world
get:
description: Returns 'Hello' to the caller
# used as the method name of the controller
operationId: hello
parameters:
- name: name
in: query
description: The name of the person to whom to say hello
required: false
type: string
responses:
"200":
description: Success
schema:
# a pointer to a definition
$ref: "#/definitions/HelloWorldResponse"
# responses may fall through to errors
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
/try:
x-swagger-router-controller: hello_world
get:
description: Returns 'Try' to the caller
operationId: try
parameters:
- name: name
in: query
description: The content to try
required: false
type: string
responses:
"200":
description: Success
schema:
$ref: "#/definitions/HelloWorldResponse"
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
/swagger:
x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
HelloWorldResponse:
required:
- message
properties:
message:
type: string
ErrorResponse:
required:
- message
properties:
message:
type: string
My doubt is how can i generate this YAML in Node.js? Is there any specific NPM package or any swagger module available to generate this kind of YAML or writing code on own is preferable?
Trying to analyze the better way to do this. I appreciate all suggestions and thanks in advance!
I've made a fresh workspace with the latest sencha cmd 5.0.2.270 and latest ExtJS 5.0.1. Generated an app into in. Wrote a little bit of code.
I generate production build with sencha app build.
The development loads well, but the production build tries to load file with no name and gets a 404
GET http://yassa-built.dev/.js?_dc=1410352524548 404 (Not Found)
After that error it doesn't load at all.
I can't understand what it is searching for. Development is not complaining at all.
I made an archive with it https://mega.co.nz/#!Dk0gDRJD!dNITsq1fGFs5T4d-4yYFnA6_K6EcAhFkxoeEjaJu7MY (~600kb). It includes the sources and the production build.
UPD
I've found the place where it starts to break. In file RadioAdminController.js.
case 'menu_referals':
return app.setSubView('redmed-radioapp-referals', {
store: Ext.create('RedmedAdmin.store.Referals')
});
If I do not create a store - it works. The production build is ok. The store is nothing special:
Ext.define('RedmedAdmin.store.Referals', {
extend: 'Ext.data.Store',
model: 'RedmedAdmin.model.Referal',
autoLoad: false,
autoSync: true
});
On the fourth day of struggling a simple answer revealed.
I've missed one dependency. The chain: RedmedAdmin.store.Referals -> RedmedAdmin.model.Referal -> RedmedAdmin.model.redmed.RadioAppBase.
As I provided the archive, I will list class RedmedAdmin.model.redmed.RadioAppBase here (working version):
Ext.define 'RedmedAdmin.model.redmed.RadioAppBase',
extend: 'Ext.data.Model'
requires: ['Ext.data.identifier.Uuid', 'Ext.data.proxy.Rest']
identifier: 'uuid'
fields: [{
name: 'id'
type: 'string'
}]
schema:
namespace: 'RedmedAdmin.model.redmed.radioapp'
proxy:
type: 'rest'
url: 'http://10.0.29.140:6543/api/rest/{entityName:lowercase}'
reader:
type: 'json'
rootProperty: '{entityName:lowercase}'
listeners:
'exception': (request, operation, eOpts ) ->
Ext.log {level: 'error'}, "Data request to #{request.url} failed. Reply: #{operation.responseText}"
It defines a schema for all children. The schema uses rest proxy (type: 'rest'). It wasn't included in the broken version. Only Ext.data.identifier.Uuid was listed in requires.
Run the app from build/testing/ to see which dependency is missing.
I had the same problem before and the fix was to add required Ext.layout.container.Border' & 'Ext.layout.container.Center'. I had to manually comment out codes & run the production build to check (since it works fine in developement mode). In some cases, it would point out the the missing dependencies like widget/...js
This problem is related to classes need to be added in the requires array. I ran the build using Sencha app build testing then in the debug I cam to know which class was loading empty. To resolve my problem I have added Ext.layout.container.Column but it can be any class, so its better to run the build in testing then identify the problem.
In order to get these configuration properties to work properly, you need to add this 'Ext.data.identifier.Uuid' class as project level.
Include Ext.data.identifier.Uuid as requires in the Ex.Application app.js file
Ext.application({
requires: [
'Ext.data.identifier.Uuid' // Include it
],
models: [
'UsersModel',
'RolesModel',
'LoginModel'
]
.
.
.
.
});