Convert API Gateway Cloudformation template to Swagger file - swagger

There is an existing API described in a Coludformation template. Now I want to document the API using Swagger. Is there a way to parse the Cloudformation template to create the swagger.yaml specification file? I would like to avoid writing the API a second time, if possible.
Note: I am aware that you can define your API using Swagger, then import the API configuration in your Cloudformation template. This is not what I need. The Cloudformation already exists and will not be changed. Hence, I need the opposite: a Swagger configuration file based on an existing Cloudformation template.

There is no way to convert the template to a swagger file that I know about. But if you are looking for a way to keep service-spec in one place only (template) and you have it deployed, you can take swagger or OAS file from the stage (so to do it you must have a stage as well) in two ways at least:
By Web console. Use Amazon API Gateway->
APIs->Your API->Stages>Your Stage -> Export tab. See the picture: exporting Swagger or OAS as a file by Web console
aws apigateway get-export ... Here is an example:
aws apigateway get-export --rest-api-id ${API_ID} --stage-name ${STAGE_NAME} --export-type swagger swagger.json

I just made this, it is not setup for perfect plug/play, but will give you an idea what you need to adjust to get it working (also need to make sure you CF template is setup so it has the needed info, on mine I had to add some missing requestParams I was missing, also use this site to test your results from this code to see it works with swagger):
const yaml = require('js-yaml');
const fs = require('fs');
// Get document, or throw exception on error
try {
// loads file from local
const inputStr = fs.readFileSync('../template.yaml', { encoding: 'UTF-8' });
// creating a schema to handle custom tags (cloud formation) which then js-yaml can handle when parsing
const CF_SCHEMA = yaml.DEFAULT_SCHEMA.extend([
new yaml.Type('!ImportValue', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::ImportValue': data };
},
}),
new yaml.Type('!Ref', {
kind: 'scalar',
construct: function (data) {
return { Ref: data };
},
}),
new yaml.Type('!Equals', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Equals': data };
},
}),
new yaml.Type('!Not', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Not': data };
},
}),
new yaml.Type('!Sub', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::Sub': data };
},
}),
new yaml.Type('!If', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::If': data };
},
}),
new yaml.Type('!Join', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Join': data };
},
}),
new yaml.Type('!Select', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Select': data };
},
}),
new yaml.Type('!FindInMap', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::FindInMap': data };
},
}),
new yaml.Type('!GetAtt', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::GetAtt': data };
},
}),
new yaml.Type('!GetAZs', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::GetAZs': data };
},
}),
new yaml.Type('!Base64', {
kind: 'mapping',
construct: function (data) {
return { 'Fn::Base64': data };
},
}),
]);
const input = yaml.load(inputStr, { schema: CF_SCHEMA });
// now that we have our AWS yaml copied and formatted into an object, lets pluck what we need to match up with the swagger.yaml format
const rawResources = input.Resources;
let guts = [];
// if an object does not contain a properties.path object then we need to remove it as a possible api to map for swagger
for (let i in rawResources) {
if (rawResources[i].Properties.Events) {
for (let key in rawResources[i].Properties.Events) {
// console.log(i, rawResources[i]);
if (rawResources[i].Properties.Events[key].Properties.Path) {
let tempResource = rawResources[i].Properties.Events[key].Properties;
tempResource.Name = key;
guts.push(tempResource);
}
}
}
} // console.log(guts);
const defaultResponses = {
'200': {
description: 'successful operation',
},
'400': {
description: 'Invalid ID supplied',
},
};
const formattedGuts = guts.map(function (x) {
if (x.RequestParameters) {
if (
Object.keys(x.RequestParameters[0])[0].includes('path') &&
x.RequestParameters.length > 1
) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
{
name: Object.keys(x.RequestParameters[1])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[1])[0].Required,
},
],
responses: defaultResponses,
},
},
};
} else if (Object.keys(x.RequestParameters[0])[0].includes('path')) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
],
responses: defaultResponses,
},
},
};
} else if (Object.keys(x.RequestParameters[0])[0].includes('querystring')) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split(
'method.request.querystring.'
)[1],
in: 'query',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
],
responses: defaultResponses,
},
},
};
}
}
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
responses: defaultResponses,
},
},
};
});
const swaggerYaml = yaml.dump(
{
swagger: '2.0',
info: {
description: '',
version: '1.0.0',
title: '',
},
paths: Object.assign({}, ...formattedGuts),
},
{ noRefs: true }
); // need to keep noRefs as true, otherwise you will see "*ref_0" instead of the response obj
// console.log(swaggerYaml);
fs.writeFile('../swagger.yaml', swaggerYaml, 'utf8', function (err) {
if (err) return console.log(err);
});
} catch (e) {
console.log(e);
console.log('error above');
}

Related

unable to get correct data using `useLazyLoadQuery` when compose fragment into query

I do see a sucessfull API request
const data = useLazyLoadQuery<brandQuery>(
graphql`query
brandQuery {
...brand_autoBrands
}
`,
{
first: 10,
},
{
fetchPolicy: "network-only",
}
);
console.log(data);
But I got following output. it is supposed to be a json object returned from my API.
brand_autoBrands fragment somewhere
const autoBrands = graphql`
fragment brand_autoBrands on AdminQuery
#argumentDefinitions(
first: { type: "Int", defaultValue: 10 }
after: { type: "String", defaultValue: "" }
last: { type: "Int" }
before: { type: "String" }
filters: { type: "[Filter]" }
sorters: { type: "[Sorter]"}
)
#refetchable(queryName: "BrandListPaginationQuery") {
autoBrands(first: $first, after: $after, last: $last, before: $before, filters: $filters, sorters: $sorters)
#connection(key: "BrandList_autoBrands") {
edges {
node {
...brandFragment
}
}
pageInfo {
startCursor
}
totalCount
}
}
`;
const {
data,
loadNext,
hasNext
} = usePaginationFragment<BrandListPaginationQuery, _>(
autoBrands,
props.autoBrands,
);
You can't log a fragment data object in the parent. That data belongs to the component that defined a fragment. For performance, relay needs to know that this data is fetched for a child component but the parent doesn't need to know what the actual data object is. You just need to pass the data to its component then you should be able to log it in the child component.
const data = useLazyLoadQuery<brandQuery>(
graphql`query
brandQuery {
...brand_autoBrands
}
`,
{
first: 10,
},
{
fetchPolicy: "network-only",
}
);
data && <Brand autoBrands={data} />

Falcor - HTTPDataSource to post Json

Is it possible to post a Json file using the falcor.browser's model? I have used the get method in it. Below is what I require, but it is not working.
<script src="./js/falcor.browser.js"></script>
function registerUser() {
var dataSource = new falcor.HttpDataSource("http://localhost/registerUser.json");
var model = new falcor.Model({
source: dataSource
});
var userJson = {"name":"John","age":"35","email":"john#abc.com"};
model.
set(userJson).
then(function(done){
console.log(done);
});
This is the server.js code:
app.use('/registerUser.json', falcorExpress.dataSourceRoute(function (req, res) {
return new Router([
{
route: "rating",
get: function() {
// Post call to external Api goes here
}
}
]);
}));
A few things:
The Model's set() method takes 1+ pathValues, so reformat your userJson object literal into a set of pathValues. Something like:
model.
set(
{ path: ['users', 'id1', 'name'], value: 'John' },
{ path: ['users', 'id1', 'age'], value: 35 },
{ path: ['users', 'id1', 'email'], value: 'john#abc.com' }
).
then(function(done){
console.log(done);
});
Second, your router must implement set handlers to correspond to the paths you are trying to set. These handlers should also return pathValues:
new Router([
{
route: 'users[{keys:ids}]["name", "age", "email"]',
set: function(jsonGraph) {
// jsonGraph looks like { users: { id1: { name: "John", age: 35, email: "john#abc.com" }
// make request to update name/age/email fields and return updated pathValues, e.g.
return [
{ path: ['users', 'id1', 'name'], value: 'John' },
{ path: ['users', 'id1', 'age'], value: 35 },
{ path: ['users', 'id1', 'email'], value: 'john#abc.com' },
];
}
}
]);
Given that your DB request is likely asynchronous, your route get handler will have to return a promise or observable. But the above should work as a demonstration.
Edit
You can also use route pattern matching on the third path key if the number of fields gets large, as was demonstrated above on the second id key.
{
route: 'users[{keys:ids}][{keys:fields}]',
set: function(jsonGraph) {
/* jsonGraph looks like
{
users: {
id1: { field1: "xxx", field2: "yyy", ... },
id1: { field1: "xxx", field2: "yyy", ... },
...
}
}
*/
}
}

JIRA - list projects in configuration and remember selection

I am trying to create a dashboard gadget that will display a list of JIRA projects in its configuration dialog and allow the user to select from the list. I need to be able to remember this list of projects (so save them on the server somehow). How do I go about doing that for a list?
I am using the latest jira version out
Thanks
Use this code in gadget.xml file:
...
<UserPref name="projectId" display_name="Project" datatype="select" default_value=""/>
...
<script type="text/javascript">
(function () {
var gadget = AJS.Gadget({
baseUrl: "__ATLASSIAN_BASE_URL__",
config: {
descriptor: function (args) {
var gadget = this;
var projects = [{"label":"All","value":""}];
projectsMap = args.projects.options;
for(key in projectsMap) {
projectName = projectsMap[key].label;
projects.push({"label":projectName,"value":projectName});
}
return {
fields: [
{
userpref: "projectId",
label: "Project",
type: "select",
selected: this.getPref("projectId"),
options: projects
},
...
AJS.gadget.fields.nowConfigured()
]
};
},
args : [{
key: "projects",
ajaxOptions: "/rest/gadget/1.0/filtersAndProjects?showFilters=false"
}]
},
view: {
enableReload: true,
template: function(args) {
var gadget = this;
...
},
args: [{
key: "timesheet",
ajaxOptions: function() {
return {
url: "/rest/timepo-resource/1.0/issues-report.json", //put your url here
data: {
projectId: this.getPref("projectId"),
...
baseUrl: "__ATLASSIAN_BASE_URL__"
}
};
}
}]
}
});
})();
</script>

Sencha touch customise rest proxy url

I need to pass addition param to jersey server. But how do I submit my url like ..get/{param1}/{param2}/{param3}
Here is my js file
Ext.define('bluebutton.view.BlueButton.testing', {
extend: 'Ext.form.Panel',
xtype: 'testing',
requires: [
'bluebutton.view.BlueButton.TransactionList',
'bluebutton.view.BlueButton.MemberPopUp',
'bluebutton.view.BlueButton.MemberDetail',
'bluebutton.store.BlueButton.MemberList',
],
config: {
id:'register',
items :[
{
xtype: 'textfield',
name: 'name',
label: 'Name'
},
{
xtype: 'emailfield',
name: 'email',
label: 'Email'
},
{
xtype: 'button',
text: 'Send',
handler: function(button) {
var form = Ext.getCmp('register');
values = form.getValues();
// Select record
//If load data , restful will using "get", url will be /users/1
var User = Ext.ModelMgr.getModel('bluebutton.model.BlueButton.MemberList');
User.load(123,
{
success: function(user) {
alert(user.get('fullName'));
}
}
);
}
}
],
}
});
Model.js
Ext.define('bluebutton.model.BlueButton.MemberList', {
extend: 'Ext.data.Model',
config: {
idProperty: 'memberModel',
fields: [
{ name: 'fullName' },
{ name: 'singer' },
],
proxy: {
type: 'rest',
url: 'http://localhost:8080/RESTFulExample/rest/json/metallica/get',
reader: 'json',
actionMethods: {
create: 'GET',
read: 'POST',
update: 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
},
writer: {
type: 'json',
},
}
}
});
But now I only able to pass my url like ..get/123 Please guide me some solution.Thanks
2 things coming to my mind, First do not write proxy inside model definition, instead set it in initialize function of store where you can look at config data and create url on its basis. e.g.
initialize: function() {
var myId = this.config.uid;
this.setProxy({
type: 'rest',
url: 'http://localhost:8080/RESTFulExample/rest/json/metallica/get/'+myId,
reader: 'json',
actionMethods: {
create: 'GET',
read: 'POST',
update: 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
},
writer: {
type: 'json',
},
});
}
and you can pass id to load when you create the store like this:
var memberStore = Ext.create('bluebutton.store.BlueButton.MemberList', {
uid : 123
});
2nd way could be writing your own proxy extending Ext.data.proxy.Rest and implementing buildUrl such that it checks for data and append it to url. e.g.
buildUrl: function(request) {
var me = this,
url = me.callParent(arguments);
if(!Ext.isEmpty(someData)){
url = Ext.urlAppend(url, "data="+someData);
}
return url;
}
I hope it helps.
EDIT
Sample code for custom proxy which I have used in past to append some token to every request
Ext.define('myapp.proxy.CustomJsonpProxy', {
extend: 'Ext.data.proxy.JsonP',
alias: 'proxy.customjsonpproxy',
buildUrl: function(request) {
var me = this,
url = me.callParent(arguments);
if(!Ext.isEmpty(loggedInUserToken)){
url = Ext.urlAppend(url, "token="+loggedInUserToken);
}
return url;
}
});
the below code worked for me....to set a param to an url
myStore.getProxy().getApi().read = myStore.getProxy().getApi().read + param;

Sencha Model.save sends /0.json to server

I've got the following code, which supposed to create a new item. Proxy type is REST.
var inst = Ext.ModelMgr.create({
title: values.title
}, "EntriesModel");
inst.save({
success: function(model) {
console.log(model);
}
});
After save(), I see that request is sent to http://localhost:3000/entries/0.json, while I assume it should have been sent to http://localhost:3000/entries
Entries model looks like this
Ext.regModel("EntriesModel", {
fields: [
{name: "id", type: "int"},
{name: "title", type: "string"},
{name: "list_id", type:"int"},
{name: "bought", type: "boolean"},
],
proxy: {
type: 'rest',
url: '/entries',
format: 'json',
noCache: true,
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
},
listeners: {
exception: function (proxy, response, operation) {
console.log(proxy, response, operation);
}
}
}
});
Backend is Rails.
Look at this, how building a link for a Rest Proxy:
buildUrl: function(request) {
var records = request.operation.records || [],
record = records[0],
format = this.format,
url = request.url || this.url;
if (this.appendId && record) {
if (!url.match(/\/$/)) {
url += '/';
}
url += record.getId();
}
if (format) {
if (!url.match(/\.$/)) {
url += '.';
}
url += format;
}
request.url = url;
return Ext.data.RestProxy.superclass.buildUrl.apply(this, arguments);
}
Override this to provide further customizations, but remember to call the superclass buildUrl
Try to read this http://dev.sencha.com/deploy/touch/docs/?class=Ext.data.RestProxy
and example:
new Ext.data.RestProxy({
url: '/users',
format: 'json'
});
// Collection url: /users.json
// Instance url : /users/123.json

Resources