Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
fmvilas committed Mar 20, 2020
0 parents commit 4b76f65
Show file tree
Hide file tree
Showing 22 changed files with 481 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
indent_style = space
indent_size = 2

[*.md]
trim_trailing_whitespace = false
82 changes: 82 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
extends: 'eslint:recommended'

parserOptions:
ecmaVersion: 8

env:
node: true
es6: true

ecmaFeatures:
forOf: true
modules: true

rules:
# Possible Errors
no-console: 0
valid-jsdoc: [0, {requireReturn: false, requireParamDescription: false, requireReturnDescription: false}]

# Best Practices
consistent-return: 0
curly: 0
block-scoped-var: 2
no-else-return: 2
no-process-env: 2
no-self-compare: 2
no-throw-literal: 2
no-void: 2
radix: 2
wrap-iife: [2, outside]

# Variables
no-shadow: 0
no-use-before-define: [2, nofunc]

# Node.js
no-process-exit: 0
handle-callback-err: [2, err]
no-new-require: 2
no-path-concat: 2

# Stylistic Issues
quotes: [2, single]
camelcase: 0
indent: [2, 2]
no-lonely-if: 2
no-floating-decimal: 2
brace-style: [2, 1tbs, { "allowSingleLine": true }]
comma-style: [2, last]
consistent-this: [0, self]
func-style: 0
max-nested-callbacks: 0
new-cap: 2
no-multiple-empty-lines: [2, {max: 1}]
no-nested-ternary: 2
semi-spacing: [2, {before: false, after: true}]
operator-assignment: [2, always]
padded-blocks: [2, never]
quote-props: [2, as-needed]
space-before-function-paren: [2, always]
keyword-spacing: [2, {"before": true, "after": true}]
space-before-blocks: [2, always]
array-bracket-spacing: [2, never]
computed-property-spacing: [2, never]
space-in-parens: [2, never]
space-unary-ops: [2, {words: true, nonwords: false}]
#spaced-line-comment: [2, always]
wrap-regex: 2
linebreak-style: [2, unix]
semi: [2, always]

# ECMAScript 6
arrow-spacing: [2, {before: true, after: true}]
no-class-assign: 2
no-const-assign: 2
no-dupe-class-members: 2
no-this-before-super: 2
no-var: 2
object-shorthand: [2, always]
prefer-arrow-callback: 2
prefer-const: 2
prefer-spread: 2
prefer-template: 2
62 changes: 62 additions & 0 deletions .filters/all.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const URL = require('url');
const path = require('path');
const _ = require('lodash');

module.exports = ({ Nunjucks }) => {
Nunjucks.addFilter('kebabCase', (string) => {
return _.kebabCase(string);
});

Nunjucks.addFilter('camelCase', (string) => {
return _.camelCase(string);
});

Nunjucks.addFilter('oneLine', (string) => {
if (!string) return string;
return string.replace(/\n/g, ' ');
});

Nunjucks.addFilter('docline', (field, fieldName, scopePropName) => {
const buildLine = (f, fName, pName) => {
const type = f.type() ? f.type() : 'string';
const description = f.description() ? ` - ${f.description().replace(/\r?\n|\r/g, '')}` : '';
let def = f.default();

if (def && type === 'string') def = `'${def}'`;

let line;
if (def !== undefined) {
line = ` * @param {${type}} [${pName ? `${pName}.` : ''}${fName}=${def}]`;
} else {
line = ` * @param {${type}} ${pName ? `${pName}.` : ''}${fName}`;
}

if (type === 'object') {
let lines = `${line}\n`;
let first = true;
for (const propName in f.properties()) {
lines = `${lines}${first ? '' : '\n'}${buildLine(f.properties()[propName], propName, `${pName ? `${pName}.` : ''}${fName}`)}`;
first = false;
}
return lines;
}

return `${line}${description}`;
};

return buildLine(field, fieldName, scopePropName);
});

Nunjucks.addFilter('port', (url, defaultPort) => {
const parsed = URL.parse(url);
return parsed.port || defaultPort || 80;
});

Nunjucks.addFilter('pathResolve', (pathName, basePath = '/') => {
return path.resolve(basePath, pathName);
});

Nunjucks.addFilter('throw', (message) => {
throw new Error(message);
});
};
18 changes: 18 additions & 0 deletions .hooks/create-asyncapi-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const fs = require('fs');
const path = require('path');

module.exports = register => {
register('generate:after', generator => {
const asyncapi = generator.originalAsyncAPI;
let extension;

try {
JSON.parse(asyncapi);
extension = 'json';
} catch (e) {
extension = 'yaml';
}

fs.writeFileSync(path.resolve(generator.targetDir, `asyncapi.${extension}`), asyncapi);
});
};
9 changes: 9 additions & 0 deletions .hooks/rename-gitignore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const fs = require('fs');
const path = require('path');

module.exports = register => {
register('generate:after', generator => {
if (generator.entrypoint && generator.entrypoint !== '__.gitignore') return;
fs.renameSync(path.resolve(generator.targetDir, '__.gitignore'), path.resolve(generator.targetDir, '.gitignore'));
});
};
9 changes: 9 additions & 0 deletions .hooks/rename-package.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const fs = require('fs');
const path = require('path');

module.exports = register => {
register('generate:after', generator => {
if (generator.entrypoint && generator.entrypoint !== '__package.json') return;
fs.renameSync(path.resolve(generator.targetDir, '__package.json'), path.resolve(generator.targetDir, 'package.json'));
});
};
Empty file added .npmignore
Empty file.
9 changes: 9 additions & 0 deletions .tp-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"supportedProtocols": ["ws"],
"parameters": {
"server": {
"description": "The server you want to use in the code.",
"required": true
}
}
}
14 changes: 14 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
FROM node:12-alpine

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Copy app source
COPY . /usr/src/app

CMD [ "npm", "start" ]
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# {{ asyncapi.info().title() }}

{{ asyncapi.info().description() | safe }}
3 changes: 3 additions & 0 deletions __.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.DS_Store
npm-debug.log
14 changes: 14 additions & 0 deletions __package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "{{ asyncapi.info().title() | kebabCase }}",
"description": "{{ asyncapi.info().description() | oneLine }}",
"version": "{{ asyncapi.info().version() }}",
"scripts": {
"start": "node src/api/index.js"
},
"dependencies": {
"asyncapi-parser": "0.x",
"express": "4.17.1",
"express-ws": "4.0.0",
"node-yaml-config": "0.0.4"
}
}
10 changes: 10 additions & 0 deletions config/common.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
default:
port: {{ asyncapi.server(params.server).url() | port }}

development:

test:

staging:

production:
61 changes: 61 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<html>
<head>
<title>{{ asyncapi.info().title() }}</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>

<body>
Open your browser console to see the logs.
<script>
let connection;

function displayHelp() {
console.log('Available channels:')
{%- for channelName, channel in asyncapi.channels() %}
{%- if channel.hasSubscribe() %}
console.log('* {{ channelName }}');
{%- endif -%}
{% endfor %}
console.log('Available commands:')
console.log('- listen: Establish a connection with the server at a given path.')
console.log(' Usage: listen(channelName)');
console.log(` Example: listen('{{ asyncapi.channelNames()[0] }}')`);
console.log('- send: Send a message to the server at a currently connected path.')
console.log(' Usage: send(message)');
console.log(` Example: send({ greet: 'Hello from client' })`);
}

function listen(path) {
const url = new URL(path, 'ws://{{ asyncapi.server(params.server).url() }}').toString()
connection = new WebSocket(url)

connection.onerror = error => {
console.log(`WebSocket error: ${error}`)
}

connection.onopen = () => {
console.log('Connected to server');
}

connection.onmessage = e => {
console.log('Server says:', e.data)
}
}

function send(message) {
if (!connection) {
console.error('You have to call listen(channelName) first. See the list of available commands and below.');
displayHelp();
return;
}
let msg = message;
if (typeof msg === 'object') msg = JSON.stringify(msg);
connection.send(msg);
console.info('Hint: check out the server logs to see your message.');
}

displayHelp();
</script>
</body>
</html>
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@asyncapi/nodejs-ws-template",
"version": "0.1.0",
"description": "Node.js WebSockets template for AsyncAPI generator.",
"keywords": [
"asyncapi",
"generator",
"nodejs",
"websockets",
"ws",
"template"
],
"author": "Fran Mendez <fmvilas@gmail.com> (fmvilas.com)",
"license": "Apache-2.0",
"dependencies": {
"lodash": "^4.17.15"
}
}
26 changes: 26 additions & 0 deletions src/api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const app = require('express')();
require('express-ws')(app);
const config = require('../lib/config');
const routes = require('./routes');
const asyncapi = require('../lib/asyncapi');

const start = async () => {
await asyncapi.init();

app.use(routes);

app.use((req, res, next) => {
res.status(404).send('Error: path not found');
next();
});

app.use((err, req, res, next) => {
console.error(err);
next();
});

app.listen(config.port);
console.info(`Listening on port ${config.port}`);
};

start();

0 comments on commit 4b76f65

Please sign in to comment.