Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP][RFC] Add local swagger ui for LoopBack 4 API explorer #1664

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/explorer/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
25 changes: 25 additions & 0 deletions packages/explorer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2018. All Rights Reserved.
Node module: @loopback/explorer
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
27 changes: 27 additions & 0 deletions packages/explorer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# @loopback/explorer

This module contains a handler to serve API Explorer

## Installation

```sh
npm install --save @loopback/explorer
```

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/blob/master/docs/CONTRIBUTING.md)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

Run `npm test` from the root folder.

## Contributors

See
[all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
7 changes: 7 additions & 0 deletions packages/explorer/docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"content": [
"index.ts",
"src/explorer.ts"
],
"codeSectionDepth": 4
}
6 changes: 6 additions & 0 deletions packages/explorer/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions packages/explorer/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions packages/explorer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
59 changes: 59 additions & 0 deletions packages/explorer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@loopback/explorer",
"version": "0.1.0",
"description": "LoopBack's API Explorer",
"engines": {
"node": ">=8.9"
},
"scripts": {
"build:apidocs": "lb-apidocs",
"build": "lb-tsc es2017 --outDir dist --copy-resources",
"clean": "lb-clean loopback-explorer*.tgz dist* package api-docs",
"pretest": "npm run build",
"integration": "lb-mocha \"dist/test/integration/**/*.js\"",
"test": "lb-mocha \"dist/test/unit/**/*.js\" \"dist/test/integration/**/*.js\"",
"unit": "lb-mocha \"dist/test/unit/**/*.js\"",
"verify": "npm pack && tar xf loopback-explorer*.tgz && tree package && npm run clean"
},
"author": "IBM",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"dependencies": {
"@loopback/context": "^1.0.0",
"@loopback/core": "^1.0.0",
"@loopback/dist-util": "^0.3.6",
"@loopback/rest": "^1.1.0",
"@types/express": "^4.16.0",
"ejs": "^2.6.1",
"serve-static": "^1.13.2",
"swagger-ui-dist": "^3.19.0"
},
"devDependencies": {
"@loopback/build": "^1.0.0",
"@loopback/testlab": "^1.0.0",
"@types/ejs": "^2.6.0",
"@types/node": "^10.10.1",
"@types/serve-static": "^1.13.2",
"express": "^4.16.3"
},
"keywords": [
"LoopBack",
"Explorer",
"Swagger"
],
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist*/src",
"dist*/index*",
"src"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git"
}
}
46 changes: 46 additions & 0 deletions packages/explorer/src/explorer.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {inject} from '@loopback/context';
import {Application, Component, CoreBindings} from '@loopback/core';
import {RestServer} from '@loopback/rest';
import {ApiExplorerUIOptions, apiExplorerUI} from './explorer';
import {ExplorerBindings} from './keys';

/**
* We have a few options:
*
* 1. The Explorer component contributes an express middleware so that REST
* servers can mount the UI
*
* 2. The Explorer component contributes a route to REST servers
*
* 3. The Explorer component proactively mount itself with the RestApplication
*/
export class ExplorerComponent implements Component {
constructor(
@inject(CoreBindings.APPLICATION_INSTANCE) private application: Application,
@inject(ExplorerBindings.CONFIG, {optional: true})
private config: ApiExplorerUIOptions,
) {
this.init();
}

init() {
// FIXME: We should be able to receive the servers via injection
const restServerBindings = this.application.find(
binding =>
binding.key.startsWith(CoreBindings.SERVERS) &&
binding.valueConstructor === RestServer,
);
for (const binding of restServerBindings) {
const restServer = this.application.getSync<RestServer>(binding.key);
restServer.bind(ExplorerBindings.MIDDLEWARE).to({
path: this.config.path || '/explorer',
handler: apiExplorerUI(this.config),
});
}
}
}
69 changes: 69 additions & 0 deletions packages/explorer/src/explorer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

const swaggerUI = require('swagger-ui-dist');

import * as path from 'path';
import * as fs from 'fs';

import {Handler} from 'express';
import * as serveStatic from 'serve-static';
import * as ejs from 'ejs';

/**
* Options to configure API Explorer UI
*/
export type ApiExplorerUIOptions = {
/**
* URL to the OpenAPI spec
*/
openApiSpecUrl?: string;

/**
* Custom EJS template for index.html
*/
indexHtmlTemplate?: string;

/**
* Options for serve-static middleware
*/
serveStaticOptions?: serveStatic.ServeStaticOptions;

/**
* Path for the explorer UI
*/
path?: string;
};

/**
* Mount the API Explorer UI (swagger-ui) to the given express router
* @param options
*/
export function apiExplorerUI(options: ApiExplorerUIOptions = {}): Handler {
const openApiSpecUrl = options.openApiSpecUrl || '/openapi.json';
const indexHtml =
options.indexHtmlTemplate || path.resolve(__dirname, './index.html.ejs');
const template = fs.readFileSync(indexHtml, 'utf-8');
const templateFn = ejs.compile(template);
const uiHandler = serveStatic(
swaggerUI.getAbsoluteFSPath(),
options.serveStaticOptions,
);

return (req, res, next) => {
if (req.path === '/' || req.path === '/index.html') {
const data = {
openApiSpecUrl,
};
const homePage = templateFn(data);
res
.status(200)
.contentType('text/html')
.send(homePage);
} else {
uiHandler(req, res, next);
}
};
}
64 changes: 64 additions & 0 deletions packages/explorer/src/index.html.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>LoopBack API Explorer</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: "<%- openApiSpecUrl %>",
dom_id: '#swagger-ui',
deepLinking: true,
filter: true,
defaultModelsExpandDepth: 0,
defaultModelExpandDepth: 0,
presets: [
SwaggerUIBundle.presets.apis,
// SwaggerUIStandalonePreset
SwaggerUIStandalonePreset.slice(1) // Disable the top bar
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"

})

window.ui = ui
}
</script>
</body>

</html>
8 changes: 8 additions & 0 deletions packages/explorer/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './explorer';
export * from './keys';
export * from './explorer.component';
21 changes: 21 additions & 0 deletions packages/explorer/src/keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {BindingKey} from '@loopback/context';
import {ApiExplorerUIOptions} from './explorer';
import {Middleware} from '@loopback/rest';

/**
* Binding keys used by this component.
*/
export namespace ExplorerBindings {
export const MIDDLEWARE = BindingKey.create<Middleware>(
'middleware.explorer',
);

export const CONFIG = BindingKey.create<ApiExplorerUIOptions | undefined>(
'explorer.config',
);
}
Loading