Skip to content

Instantly share code, notes, and snippets.

@x5engine
Created August 5, 2020 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x5engine/22dd596ef07961b527f9f3ad3303da60 to your computer and use it in GitHub Desktop.
Save x5engine/22dd596ef07961b527f9f3ad3303da60 to your computer and use it in GitHub Desktop.
import koa from "koa";
import Router from "koa-router";
import logger from "koa-logger";
import json from "koa-json";
import bodyParser from "koa-bodyparser";
import serve from "koa-static";
import websockify from "koa-websocket";
import cors from "@koa/cors";
import { createReadStream } from 'fs';
import dotenv from "dotenv";
import wss from "./wss";
import api from "./api";
dotenv.config();
if (
!process.env.USER_API_KEY ||
!process.env.USER_API_SECRET
) {
process.exit(1);
}
const PORT = parseInt(process.env.PORT, 10) || 3001;
const app = websockify(new koa());
/** Middlewares */
app.use( json() );
app.use( logger() );
app.use( bodyParser() );
/* Not safe in production */
app.use(cors());
// app.use(serve(__dirname + '/../client'));
/**
* Start HTTP Routes
*/
const router = new Router();
app.use( router.routes() ).use( router.allowedMethods() );
/**
* Serve index.html
*/
router.get( '/', async (ctx: koa.Context, next: () => Promise<any>) => {
// ctx.type = 'text/html; charset=utf-8';
// ctx.body = createReadStream(__dirname + '/../client/index.html');
await next();
});
/**
* Create Rest endpoint for server-side token issue
*
* See ./api.ts
*/
app.use( api.routes() );
app.use( api.allowedMethods() );
/**
* Create Websocket endpoint for client-side token challenge
*
* See ./wss.ts
*/
app.ws.use(wss);
/** Start the server! */
app.listen( PORT, () => console.log( "Server started on "+ PORT ) );
{
"name": "project-server",
"scripts": {
"start": "ts-node index.ts",
"dev": "nodemon -x ts-node src/config/server.ts"
},
"dependencies": {
"@textile/hub": "^0.4.1",
"dotenv": "^8.2.0",
"emittery": "^0.7.1",
"isomorphic-ws": "^4.0.1",
"koa": "^2.13.0",
"koa-bodyparser": "^4.3.0",
"koa-json": "^2.0.2",
"koa-logger": "^3.2.1",
"koa-route": "^3.2.0",
"koa-router": "^9.1.0",
"koa-websocket": "^6.0.0",
"ts-node": "^8.10.2",
"typescript": "^3.9.7"
}
}
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "./server",
"rootDir": "./",
"baseUrl": "/"
},
"exclude": [
"node_modules"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment