Commit c795d901 authored by Alex Quispe's avatar Alex Quispe
Browse files

Se integró el servidor para ejecutar swagger.

parent d3252fb4
......@@ -36,7 +36,7 @@ class ApidocGenerator {
await require(filePath)()
}
if (ApidocGenerator.COMPILE) {
const outputApidocPath = path.resolve(ApidocGenerator.BUILD_PATH, 'apidoc')
const outputApidocPath = path.resolve(ApidocGenerator.BUILD_PATH, 'public')
if (util.isDir(outputApidocPath)) { util.rmdir(outputApidocPath) }
util.mkdir(outputApidocPath)
......@@ -157,7 +157,7 @@ class ApidocGenerator {
content = {
"swagger": "2.0",
"info": {
"description": "Apidoc Swagger",
"description": `ApidocJS: ${ApidocGenerator.DOC_URL}/apidoc`,
"version": "1.0.0",
"title": "Apidoc",
},
......@@ -199,7 +199,8 @@ class ApidocGenerator {
}
ApidocGenerator.BUILD_PATH = path.resolve(process.cwd(), `build`)
ApidocGenerator.API_URL = 'http://localhost'
ApidocGenerator.API_URL = 'http://localhost:4000'
ApidocGenerator.DOC_URL = 'http://localhost:5000'
ApidocGenerator.COMPILE = true
function _toWords (text) {
......@@ -260,8 +261,13 @@ function _request (method, uri, body, headers) {
if (headers) { options.headers = headers }
return new Promise((resolve, reject) => {
return request(options, (error, response, body) => {
if (error) {
if (error.code === 'ECONNREFUSED') {
console.log(' El servicio a documentar no se encuentra disponible :(\n')
}
console.log(error); return reject(error)
}
const CODE = response.statusCode
if (error) { console.log(error); return reject(error) }
try { if (typeof body === 'string') body = JSON.parse(body) } catch (e) {}
if (CODE >= 200 && CODE < 300) { return resolve(body) }
return reject(new Error(`Hubo un error al procesar la petición [${method}] ${uri}\n\n${body}`))
......@@ -277,7 +283,7 @@ async function _build () {
if(util.isFile(filePath1)) { util.removeFile(filePath1) }
let content = ''
util.find(ApidocGenerator.BUILD_PATH, '.js', (info) => {
util.find(path.resolve(ApidocGenerator.BUILD_PATH, 'routes'), '.js', (info) => {
const newBlock = util.readFile(info.filePath)
const newRouteKey = newBlock.split('\n')[2]
if (content.includes(newRouteKey)) {
......@@ -293,7 +299,7 @@ async function _build () {
if(util.isFile(filePath2)) { util.removeFile(filePath2) }
let content2 = null
util.find(ApidocGenerator.BUILD_PATH, '.json', (info) => {
util.find(path.resolve(ApidocGenerator.BUILD_PATH, 'routes'), '.json', (info) => {
const contentToAdd = require(info.filePath)
if (!content2) {
content2 = contentToAdd
......@@ -315,12 +321,13 @@ async function _build () {
})
util.writeFile(filePath2, JSON.stringify(content2, null, 2))
await _buildApidocJS()
util.copyFile(path.resolve(ApidocGenerator.BUILD_PATH, `swagger.json`), path.resolve(ApidocGenerator.BUILD_PATH, `apidoc/swagger.json`))
util.copyFile(path.resolve(ApidocGenerator.BUILD_PATH, `swagger.json`), path.resolve(ApidocGenerator.BUILD_PATH, `public/swagger.json`))
}
async function _buildApidocJS () {
const templatePath = path.resolve(__dirname, '../template/apidocjs')
const tmpPath = path.resolve(__dirname, '../.temp')
const templatePath = path.resolve(__dirname, '../template/apidocjs')
const templatePathSwagger = path.resolve(__dirname, '../template/swagger')
const tmpPath = path.resolve(__dirname, '../.temp')
util.mkdir(tmpPath)
const apidocConfig = {
title : 'Apidoc',
......@@ -338,7 +345,8 @@ async function _buildApidocJS () {
}
util.writeFile(path.resolve(tmpPath, 'apidoc.json'), JSON.stringify(apidocConfig, null, 2))
util.copyFile(path.resolve(ApidocGenerator.BUILD_PATH, `apidoc.js`), path.resolve(tmpPath, `apidoc.js`))
const output = path.resolve(ApidocGenerator.BUILD_PATH, 'apidoc')
const output = path.resolve(ApidocGenerator.BUILD_PATH, 'public/apidoc')
await util.copyDir(templatePathSwagger, path.resolve(ApidocGenerator.BUILD_PATH, 'public/swagger-ui'))
try { util.rmdir(output) } catch (e) { }
try {
await _createApidoc('.', output, templatePath, tmpPath)
......
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
const PORT = process.env.DOC_PORT || 5000
const APIDOC_PATH = path.resolve(__dirname, 'build/public')
// view engine setup
app.set('views', APIDOC_PATH)
app.set('view engine', 'ejs')
app.engine('html', require('ejs').renderFile)
app.use(cors({
'origin' : '*',
'methods' : 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
'preflightContinue' : true,
'Access-Control-Allow-Headers' : '*'
}))
// public
app.use(express.static(APIDOC_PATH))
// open index.html
app.get('/', function(req, res) {
res.redirect(`/swagger-ui/index.html?url=http://localhost:${PORT}/swagger.json`)
})
// run server
app.listen(PORT, function() {
console.log(`\n Servidor para la documentación activo: http://localhost:${PORT}\n`)
})
const ApiGen = require('../../')
const path = require('path')
ApiGen.API_URL = 'http://localhost:4000'
ApiGen.API_URL = 'http://localhost:4000'
ApiGen.DOC_URL = 'http://localhost:5000'
ApiGen.SRC_PATH = path.resolve(__dirname, 'src')
ApiGen.BUILD_PATH = path.resolve(__dirname, 'build')
......
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()
const PORT = process.env.SWAGGER_PORT || '5000'
app.use(express.static(pathToSwaggerUi))
app.listen(PORT)
console.log(`\n Swagger UI activo: http://localhost:${PORT}\n`)
This diff is collapsed.
......@@ -6,8 +6,8 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"app": "node example/service/app",
"swagger": "node example/swagger-server.js",
"example": "node example/documentation && rm -rf public/apidoc && mkdir -p public/apidoc && cp -rf example/documentation/build/apidoc public"
"example": "node example/documentation && rm -rf public && cp -rf example/documentation/build/public public",
"doc-server": "node example/documentation/doc-server.js"
},
"author": "AGETIC",
"license": "GPL v2",
......@@ -20,14 +20,12 @@
},
"dependencies": {
"apidoc": "^0.17.6",
"cors": "^2.8.4",
"ejs": "^2.6.1",
"express": "^4.16.4",
"lodash": "^4.17.11",
"mkdirp": "^0.5.1",
"request": "^2.88.0",
"sequelize": "^4.39.1"
},
"devDependencies": {
"cors": "^2.8.4",
"express": "^4.16.4",
"swagger-ui-dist": "^3.19.3"
}
}
......@@ -16,7 +16,7 @@
<script id="template-sidenav" type="text/x-handlebars-template">
<nav id="scrollingNav">
<div class="sidenav-search">
<div class="pagina-inicio"><a href="./../../">Página de inicio</a></div>
<div class="pagina-inicio"><a href="./../../">Swagger UI</a></div>
<input class="form-control search" type="text" placeholder="{{__ "Buscar ..."}}">
<span class="search-reset">x</span>
</div>
......
# Swagger UI Dist
[![NPM version](https://badge.fury.io/js/swagger-ui-dist.svg)](http://badge.fury.io/js/swagger-ui-dist)
# API
This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module.
Use `swagger-ui` instead, if you'd like to have npm install dependencies for you.
`SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported:
```javascript
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
```
To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method:
```javascript
const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath()
// then instantiate server that serves files from the swaggerUiAssetPath
```
For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository.
/*
* getAbsoluteFSPath
* @return {string} When run in NodeJS env, returns the absolute path to the current directory
* When run outside of NodeJS, will return an error message
*/
const getAbsoluteFSPath = function () {
// detect whether we are running in a browser or nodejs
if (typeof module !== "undefined" && module.exports) {
return require("path").resolve(__dirname)
}
throw new Error('getAbsoluteFSPath can only be called within a Nodejs environment');
}
module.exports = getAbsoluteFSPath
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body
{
margin:0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
</body>
</html>
try {
module.exports.SwaggerUIBundle = require("./swagger-ui-bundle.js")
module.exports.SwaggerUIStandalonePreset = require("./swagger-ui-standalone-preset.js")
} catch(e) {
// swallow the error if there's a problem loading the assets.
// allows this module to support providing the assets for browserish contexts,
// without exploding in a Node context.
//
// see https://github.com/swagger-api/swagger-ui/issues/3291#issuecomment-311195388
// for more information.
}
// `absolutePath` and `getAbsoluteFSPath` are both here because at one point,
// we documented having one and actually implemented the other.
// They were both retained so we don't break anyone's code.
module.exports.absolutePath = require("./absolute-path.js")
module.exports.getAbsoluteFSPath = require("./absolute-path.js")
<!doctype html>
<html lang="en-US">
<body onload="run()">
</body>
</html>
<script>
'use strict';
function run () {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) {
qp = window.location.hash.substring(1);
} else {
qp = location.search.substring(1);
}
arr = qp.split("&")
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
qp = qp ? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === "" ? value : decodeURIComponent(value)
}
) : {}
isValid = qp.state === sentState
if ((
oauth2.auth.schema.get("flow") === "accessCode"||
oauth2.auth.schema.get("flow") === "authorizationCode"
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "warning",
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
});
}
if (qp.code) {
delete oauth2.state;
oauth2.auth.code = qp.code;
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
} else {
let oauthErrorMsg
if (qp.error) {
oauthErrorMsg = "["+qp.error+"]: " +
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
(qp.error_uri ? "More info: "+qp.error_uri : "");
}
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "error",
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
});
}
} else {
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
}
window.close();
}
</script>
{
"_from": "swagger-ui-dist",
"_id": "swagger-ui-dist@3.19.3",
"_inBundle": false,
"_integrity": "sha512-bHH4yJrOpNCxLPqoEx2ZdwSuLMmc+V3JmFM9oetqWKKRv9AgUnrO1XNhePe9uc53QPaeJ0nCf3cLCxJBle6hjA==",
"_location": "/swagger-ui-dist",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "swagger-ui-dist",
"name": "swagger-ui-dist",
"escapedName": "swagger-ui-dist",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.19.3.tgz",
"_shasum": "b1e38b1497a884500788cde919517d83554af5e8",
"_spec": "swagger-ui-dist",
"_where": "/home/wquispe/PROJECTS/BPM/agetic-bpm-backend-0.2.1",
"bugs": {
"url": "https://github.com/swagger-api/swagger-ui/issues"
},
"bundleDependencies": false,
"contributors": [
{
"url": "in alphabetical order"
},
{
"name": "Anna Bodnia",
"email": "anna.bodnia@gmail.com"
},
{
"name": "Buu Nguyen",
"email": "buunguyen@gmail.com"
},
{
"name": "Josh Ponelat",
"email": "jponelat@gmail.com"
},
{
"name": "Kyle Shockey",
"email": "kyleshockey1@gmail.com"
},
{
"name": "Robert Barnwell",
"email": "robert@robertismy.name"
},
{
"name": "Sahar Jafari",
"email": "shr.jafari@gmail.com"
}
],
"dependencies": {},
"deprecated": false,
"description": "[![NPM version](https://badge.fury.io/js/swagger-ui-dist.svg)](http://badge.fury.io/js/swagger-ui-dist)",
"devDependencies": {},
"homepage": "https://github.com/swagger-api/swagger-ui#readme",
"license": "Apache-2.0",
"main": "index.js",
"name": "swagger-ui-dist",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/swagger-api/swagger-ui.git"
},
"version": "3.19.3"
}
This diff is collapsed.
This diff is collapsed.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment