aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitlab-ci.yml5
-rw-r--r--package.json8
-rw-r--r--src/FileRouter.ts856
-rw-r--r--src/app.ts55
-rw-r--r--src/db/initPostgresDB.ts26
-rw-r--r--src/index.ts25
-rw-r--r--src/serverConfig.ts201
-rw-r--r--tsconfig.json3
-rw-r--r--tslint.json302
9 files changed, 947 insertions, 534 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index a223246..58a14ef 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -17,3 +17,8 @@ mocha:
stage: test
script:
- npm test
+
+lint:
+ stage: test
+ script:
+ - npm run _gl-lint
diff --git a/package.json b/package.json
index 381ff95..e80264b 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,9 @@
"scripts": {
"test": "mocha --reporter spec -r ts-node/register 'test/**/*.test.ts'",
"docs": "typedoc --out 'docs' --readme 'README.md' --name 'St Andrews Junior Honours 2017/18 - Team BE4' --module commonjs --target ES5 --exclude '*.test.ts' --includeDeclarations --excludeExternals 'src'",
- "start": "ts-node src/index.ts"
+ "start": "ts-node src/index.ts",
+ "lint": "tslint --fix --force -p './tsconfig.json'",
+ "_gl-lint": "tslint -p './tsconfig.json'"
},
"repository": {
"type": "git",
@@ -29,13 +31,15 @@
"chai-http": "^3.0.0",
"mocha": "^3.1.2",
"nodemon": "^1.14.10",
- "typedoc": "^0.10.0"
+ "typedoc": "^0.10.0",
+ "tslint": "^5.9.1"
},
"dependencies": {
"@types/body-parser": "0.0.33",
"@types/express": "^4.0.33",
"@types/morgan": "^1.7.32",
"@types/node": "^6.0.46",
+ "@types/sequelize": "^4.27.5",
"body-parser": "^1.18.2",
"express": "^4.16.2",
"morgan": "^1.9.0",
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 19a9126..8b12d0f 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -1,403 +1,469 @@
-import {Router, Request, Response, NextFunction} from 'express';
-var serverConfig = require('./serverConfig');
-const Files = null;//require('../data');
-
+import { NextFunction, Request, Response, Router } from 'express';
+import { Property, default as serverConfig,
+ propertyExists } from './serverConfig';
+
+/**
+ * The type of an Express middleware callback.
+ */
+type Middleware =
+ (req: Request, res: Response, next: NextFunction) => void;
+
+/*
+ * Returns the supported Protocols
+ *
+ * The server's unwrapped response MUST match:
+
+ exactly({
+ "supported": array(string),
+ "required": array(string)
+ })
+ */
+const getProtocols: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ const returnValue: {
+ supported: string[];
+ required: string[];
+ } = {
+ supported: [
+ 'BE50'
+ ],
+ required: [
+ 'BE01'
+ ]
+ };
+ res.send(JSON.stringify(returnValue));
+};
+
+/*
+ * Logging Endpoint for all components:
+ *
+ * with a request matching
+
+ array({
+ "component": string,
+ "level": alternative([
+ "info", "security", "warning", "error", "critical"
+ ]),
+ "value": anything
+ })
+ */
+const postLog: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(501)
+ .send({error: 'logging_not_enabled'});
+};
+
+/*
+ * Clients authorised as a user with the admin privilege can access
+ *
+ * http://backend.endpoint/log?before=<datetime>&after=<datetime>&level=<level>
+ *
+ * the server response should match
+
+ array({
+ "component": string,
+ "level": alternative(
+ ["info", "security", "warning", "error", "critical"
+ ]),
+ "value": anything,
+ "username": string,
+ "timestamp": string
+ })
+ */
+const getLog: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(501)
+ .send({error: 'logging_not_enabled'});
+};
+
+/*
+ * Any authenticated client can access
+ *
+ * http://backend.endpoint/properties
+ *
+ * the server SHOULD respond with a list of properties,
+ * with the unwrapped response matching
+
+ array({
+ "id": string,
+ "display": optional({
+ "category": string,
+ "group": string,
+ "display_name": string,
+ "description": string
+ }),
+ "read_only": boolean,
+ "type": alternative(["string", "integer", "boolean"]),
+ "value": alternative([string, integer, boolean])
+ })
+ */
+const getProperties: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.send(serverConfig);
+};
+
+/*
+ * To update properties the client POSTs to
+ *
+ * http://backend.endpoint/properties?action=update
+ *
+ * with body
+
+ array({
+ "id": string,
+ "value": alternative([string, integer, boolean])
+ })
+ */
+const postProperties: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ let success: boolean = true;
+
+ // For each property to update
+ let prop: Property;
+ for (prop of req.body) {
+
+ // Check that the property has an ID and a value
+ if (!prop.hasOwnProperty('id') || !prop.hasOwnProperty('value')) {
+ res.status(400)
+ .send({
+ error: 'invalid_request',
+ error_description: 'A supplied property is missing an id or value'
+ });
+ success = false;
+ break;
+ }
+
+ // Find out if the property exists in the config and if so, at which index
+ const index: number = propertyExists(prop.id);
+
+ // Check some of the properties values to ensure that it can be updated
+ if (index === -1 || serverConfig[index].readOnly) {
+ /* TODO Implement an or, using Tom's type checker to ensure
+ * the value is "valid" based on the type of the property */
+ const description: string =
+ index === -1
+ ? 'Property not found'
+ : 'Property is Read_Only';
+ res.status(400)
+ .send({
+ error: 'invalid_property',
+ error_data: prop.id,
+ error_description: description
+ });
+ success = false;
+ break;
+ }
+
+ // Make the update to the property
+ serverConfig[index].value = prop.value;
+ }
+
+ // Tell the client that everything was okay;
+ if (success) {
+ res.status(200)
+ .send();
+ }
+};
+
+/*
+ * Listing available privileges
+ *
+ * And the server's response, unwrapped, must match
+
+ array({
+ "privilege": string,
+ "description": string,
+ "internal": boolean
+ })
+ */
+const getUserPriveleges: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Listing users
+ *
+ * If the client is authorised as a user with the admin privilege
+ * the server MUST respond with a list of users,
+ * with the unwrapped response matching
+
+ array({
+ "username": string,
+ "privileges": array(string),
+ "projects": array({
+ "project_name": string,
+ "access_level": string
+ }),
+ "public_user_metadata": metadata,
+ "private_user_metadata": metadata,
+ "public_admin_metadata": metadata,
+ "private_admin_metadata": metadata
+ })
+ */
+const getUsers: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+
+};
+
+/*
+ * expose additional configuration options for individual users
+ *
+ *
+ */
+const getUserProperties: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Listing a particular User
+ *
+ * If the client is authorised as a user with the admin privilege
+ * the server MUST respond with details of the particular user
+ * if they exist (unwrapped response):
+
+ {
+ "username": string,
+ "privileges": array(string),
+ "projects": array({
+ "project_name": string,
+ "access_level": string
+ }),
+ "public_user_metadata": metadata,
+ "private_user_metadata": metadata,
+ "public_admin_metadata": metadata,
+ "private_admin_metadata": metadata
+ }
+ */
+const getUsername:
+ (req: Request, res: Response, next: NextFunction, user?: string) => void =
+ (req: Request, res: Response, next: NextFunction, user?: string): void => {
+ res.status(500)
+ .send();
+};
+
+const getCurUser: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+ const curUser: string = '';
+ getUsername(req, res, next, curUser);
+};
+
+/*
+ * Updating the current user
+ *
+ * http://backend.endpoint/current_user?action=update
+ *
+ * with body matching
+
+ {
+ "password": optional({
+ "old": string,
+ "new": string
+ }),
+ "public_user_metadata": optional(metadata),
+ "private_user_metadata": optional(metadata),
+ "public_admin_metadata": not_present,
+ "private_admin_metadata": not_present
+ }
+*/
+const postCurUser: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Creating a User/updating a user
+ *
+ * http://backend.endpoint/users/<username>?action=create
+ *
+ * with body matching
+
+ {
+ "privileges": array(string),
+ "password": string,
+ "public_user_metadata": optional(metadata),
+ "private_user_metadata": optional(metadata),
+ "public_admin_metadata": optional(metadata),
+ "private_admin_metadata": optional(metadata)
+ }
+ */
+const postUsername: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Listing available Roles
+ *
+ * The servers response, unwrapped, must match
+
+ array({
+ "role": string,
+ "description": string,
+ "internal": boolean
+ })
+ */
+const getProjectRoles: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Listing Projects
+ *
+ * The server MUST respond with a list of projects,
+ * with the unwrapped response matching
+
+ array({
+ "project_name": string,
+ "users": array({
+ "username": string,
+ "access_level": string
+ }),
+ "public_metadata": metadata,
+ "private_metadata": optional(metadata),
+ "admin_metadata": optional(metadata)
+ })
+ */
+const getProjects: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Listing a specific Project
+ *
+ * The server MUST respond with details of the particular project
+ * if it exists (unwrapped response):
+
+ {
+ "project_name": string,
+ "users": array({
+ "username": string,
+ "access_level": string
+ }),
+ "public_metadata": metadata,
+ "private_metadata": metadata,
+ "admin_metadata": optional(metadata)
+ }
+ */
+const getProjectName: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * Creating a Project / updating a project / deleting / Project grants
+ *
+ * http://backend.endpoint/projects/<project_name>?action=create
+ *
+ * with body matching
+
+ {
+ "public_metadata": optional(metadata),
+ "private_metadata": optional(metadata),
+ "admin_metadata": optional(metadata)
+ }
+ */
+const postProjectName: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/*
+ * additional configuration options for individual projects
+ */
+const getProjectProperties: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/**
+ * GET a File.
+ */
+const getFilePath: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/**
+ * GET a File.
+ */
+const getFileId: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
+
+/**
+ * Post a File. / delete / move / etc
+ */
+const postFilePath: Middleware =
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.status(500)
+ .send();
+};
export class FileRouter {
- router: Router
-
- /**
- * Initialize the FileRouter
- */
- constructor() {
- this.router = Router();
- this.init();
- }
-
- /*
- * Returns the supported Protocols
- *
- * The server's unwrapped response MUST match:
-
- exactly({
- "supported": array(string),
- "required": array(string)
- })
- */
- public getProtocols(req: Request, res: Response, next: NextFunction){
- var returnValue = {};
- returnValue['supported'] = ["BE50"];
- returnValue['required'] = "BE01";
- res.send(JSON.stringify(returnValue));
- }
-
- /*
- * Logging Endpoint for all components:
- *
- * with a request matching
-
- array({
- "component": string,
- "level": alternative(["info", "security", "warning", "error", "critical"]),
- "value": anything
- })
- */
- public postLog(req: Request, res: Response, next: NextFunction){
- res.status(501).send({error : "logging_not_enabled"});
- }
-
- /*
- * Clients authorised as a user with the admin privilege can access
- *
- * http://backend.endpoint/log?before=<datetime>&after=<datetime>&level=<level>
- *
- * the server response should match
-
- array({
- "component": string,
- "level": alternative(["info", "security", "warning", "error", "critical"]),
- "value": anything,
- "username": string,
- "timestamp": string
- })
- */
- public getLog(req: Request, res: Response, next: NextFunction){
- res.status(501).send({error : "logging_not_enabled"});
- }
-
- /*
- * Any authenticated client can access
- *
- * http://backend.endpoint/properties
- *
- * the server SHOULD respond with a list of properties, with the unwrapped response matching
-
- array({
- "id": string,
- "display": optional({
- "category": string,
- "group": string,
- "display_name": string,
- "description": string
- }),
- "read_only": boolean,
- "type": alternative(["string", "integer", "boolean"]),
- "value": alternative([string, integer, boolean])
- })
- */
- public getProperties(req: Request, res: Response, next: NextFunction){
- res.status(200).send(serverConfig.default);
- }
-
- /*
- * To update properties the client POSTs to
- *
- * http://backend.endpoint/properties?action=update
- *
- * with body
-
- array({
- "id": string,
- "value": alternative([string, integer, boolean])
- })
- */
- public postProperties(req: Request, res: Response, next: NextFunction){
- var success = true;
-
- //For each property to update
- for (var prop of req.body) {
-
- //Check that the property has and id and a value
- if (!prop.hasOwnProperty("id") || !prop.hasOwnProperty("value")) {
- res.status(400).send({error : "invalid_request", error_description : "A supplied property is missing an id or value"});
- success = false;
- break;
- }
-
- //Find out if the property exists in the config and if so, at which index
- var index = serverConfig.propertyExists(prop.id);
-
- //check some of the properties values to ensure that it can be updated
- if (index == -1 || serverConfig.default[index].read_only) { /*TODO Implement an or, using Tom's type checker to ensure the value is "valid" based on the type of the property */
- var description = index == -1 ? "Property not found" : "Property is Read_Only";
- res.status(400).send({error : "invalid_property", error_data : prop.id, error_description : description});
- success = false;
- break;
- }
-
- //make the update to the property
- serverConfig.default[index].value = prop.value;
- }
-
- //tell the client that everything was okay;
- if (success) res.status(200).send();
- }
-
- /*
- * Listing available privileges
- *
- * And the server's response, unwrapped, must match
-
- array({
- "privilege": string,
- "description": string,
- "internal": boolean
- })
- */
- public getUserPriveleges(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * Listing users
- *
- * If the client is authorised as a user with the admin privilege
- * the server MUST respond with a list of users, with the unwrapped response matching
-
- array({
- "username": string,
- "privileges": array(string),
- "projects": array({
- "project_name": string,
- "access_level": string
- }),
- "public_user_metadata": metadata,
- "private_user_metadata": metadata,
- "public_admin_metadata": metadata,
- "private_admin_metadata": metadata
- })
- */
- public getUsers(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
-
- }
-
- /*
- * expose additional configuration options for individual users
- *
- *
- */
- public getUserProperties(req: Request, res: Response, next: NextFunction, user?: String){
- res.status(500).send();
- }
-
- /*
- * Listing a particular User
- *
- * If the client is authorised as a user with the admin privilege the server MUST respond with details of the particular user if they exist (unwrapped response):
-
- {
- "username": string,
- "privileges": array(string),
- "projects": array({
- "project_name": string,
- "access_level": string
- }),
- "public_user_metadata": metadata,
- "private_user_metadata": metadata,
- "public_admin_metadata": metadata,
- "private_admin_metadata": metadata
- }
- */
- public getUsername(req: Request, res: Response, next: NextFunction, user?: String){
- res.status(500).send();
- }
-
- public getCurUser(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- let curUser : String = "";
- this.getUsername(req, res, next, curUser);
- }
-
- /*
- * Updating the current user
- *
- * http://backend.endpoint/current_user?action=update
- *
- * with body matching
-
- {
- "password": optional({
- "old": string,
- "new": string
- }),
- "public_user_metadata": optional(metadata),
- "private_user_metadata": optional(metadata),
- "public_admin_metadata": not_present,
- "private_admin_metadata": not_present
- }
- */
- public postCurUser(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
-
- }
-
- /*
- * Creating a User/updating a user
- *
- * http://backend.endpoint/users/<username>?action=create
- *
- * with body matching
-
- {
- "privileges": array(string),
- "password": string,
- "public_user_metadata": optional(metadata),
- "private_user_metadata": optional(metadata),
- "public_admin_metadata": optional(metadata),
- "private_admin_metadata": optional(metadata)
- }
- */
- public postUsername(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * Listing available Roles
- *
- * The servers response, unwrapped, must match
-
- array({
- "role": string,
- "description": string,
- "internal": boolean
- })
- */
- public getProjectRoles(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * Listing Projects
- *
- * The server MUST respond with a list of projects, with the unwrapped response matching
-
- array({
- "project_name": string,
- "users": array({
- "username": string,
- "access_level": string
- }),
- "public_metadata": metadata,
- "private_metadata": optional(metadata),
- "admin_metadata": optional(metadata)
- })
- */
- public getProjects(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * Listing a specific Project
- *
- * The server MUST respond with details of the particular project if it exists (unwrapped response):
-
- {
- "project_name": string,
- "users": array({
- "username": string,
- "access_level": string
- }),
- "public_metadata": metadata,
- "private_metadata": metadata,
- "admin_metadata": optional(metadata)
- }
- */
- public getProjectName(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * Creating a Project / updating a project / deleting / Project grants
- *
- * http://backend.endpoint/projects/<project_name>?action=create
- *
- * with body matching
-
- {
- "public_metadata": optional(metadata),
- "private_metadata": optional(metadata),
- "admin_metadata": optional(metadata)
- }
- */
- public postProjectName(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /*
- * additional configuration options for individual projects
- */
- public getProjectProperties(req: Request, res: Response, next: NextFunction){
- res.status(500).send();
- }
-
- /**
- * GET a File.
- */
- public getFile_path(req: Request, res: Response, next: NextFunction) {
- res.status(500).send();
- // let fileID = req.params.file;
- //
- // res.send("File");
- }
-
- /**
- * GET a File.
- */
- public getFile_id(req: Request, res: Response, next: NextFunction) {
- res.status(500).send();
- // let fileID = req.params.file;
- //
- // res.send("File");
- }
-
-
- /**
- * Post a File. / delete / move / etc
- */
- public postFile_path(req: Request, res: Response, next: NextFunction) {
- // let fileID = req.params.file;
- //
- // res.send("File");
- res.status(500).send();
- }
-
-
- /**
- * Take each handler, and attach to one of the Express.Router's
- * endpoints.
- */
- init() {
- // General
- this.router.get ('/_supported_protocols_', this.getProtocols);
- this.router.get ('/log', this.getLog);
- this.router.post('/log', this.postLog);
- this.router.get ('/properties', this.getProperties);
- this.router.post('/properties', this.postProperties);
- // Users
- this.router.get ('/user_privileges', this.getUserPriveleges);
- this.router.get ('/users', this.getUsers);
- this.router.get ('/users/:username', this.getUsername);
- this.router.post('/users/:username', this.postUsername);
- this.router.get ('/users/:username/properties', this.getUserProperties);
- this.router.get ('/current_user', this.getCurUser);
- this.router.post('/current_user', this.postCurUser);
- // Projects
- this.router.get ('/project_roles', this.getProjectRoles);
- this.router.get ('/projects', this.getProjects);
- this.router.get ('/projects/:project_name', this.getProjectName);
- this.router.post('/projects/:project_name', this.postProjectName);
- this.router.get ('/projects/:project_name/properties', this.getProjectProperties);
- // File access
- this.router.get ('/projects/:project_name/files/:path', this.getFile_path);
- this.router.post('/projects/:project_name/files/:id', this.postFile_path);
- this.router.get ('/projects/:project_name/files_by_id/:id', this.getFile_id);
- }
-
+ public router: Router;
+
+ /**
+ * Initialize the FileRouter
+ */
+ public constructor() {
+ this.router = Router();
+ this.init();
+ }
+
+ /**
+ * Take each handler, and attach to one of the Express.Router's
+ * endpoints.
+ */
+ public init(): void {
+ // General
+ this.router.get ('/_supported_protocols_', getProtocols);
+ this.router.get ('/log', getLog);
+ this.router.post('/log', postLog);
+ this.router.get ('/properties', getProperties);
+ this.router.post('/properties', postProperties);
+ // Users
+ this.router.get ('/user_privileges', getUserPriveleges);
+ this.router.get ('/users', getUsers);
+ this.router.get ('/users/:username', getUsername);
+ this.router.post('/users/:username', postUsername);
+ this.router.get ('/users/:username/properties', getUserProperties);
+ this.router.get ('/current_user', getCurUser);
+ this.router.post('/current_user', postCurUser);
+ // Projects
+ this.router.get ('/project_roles', getProjectRoles);
+ this.router.get ('/projects', getProjects);
+ this.router.get ('/projects/:project_name', getProjectName);
+ this.router.post('/projects/:project_name', postProjectName);
+ this.router.get ('/projects/:project_name/properties', getProjectProperties);
+ // File access
+ this.router.get ('/projects/:project_name/files/:path', getFilePath);
+ this.router.post('/projects/:project_name/files/:id', postFilePath);
+ this.router.get ('/projects/:project_name/files_by_id/:id', getFileId);
+ }
}
// Create the FileRouter, and export its configured Express.Router
-const fileRoutes = new FileRouter();
+const fileRoutes: FileRouter = new FileRouter();
fileRoutes.init();
export default fileRoutes.router;
diff --git a/src/app.ts b/src/app.ts
index 83bf2b0..c81be8a 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -1,37 +1,36 @@
-import * as express from 'express';
-import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
+import * as ex from 'express';
import FileRouter from './FileRouter';
-
+import * as logger from 'morgan';
class App {
- public express
+ public express: ex.Express;
- constructor () {
- this.express = express()
- this.middleware()
- this.mountRoutes()
- }
+ public constructor() {
+ this.express = ex();
+ this.middleware();
+ this.mountRoutes();
+ }
- // Configure Express middleware.
- private middleware(): void {
- this.express.use(logger('combined'));
- this.express.use(bodyParser.json());
- this.express.use(bodyParser.urlencoded({ extended: false }));
- }
+ // Configure Express middleware.
+ private middleware(): void {
+ this.express.use(logger('combined'));
+ this.express.use(bodyParser.json());
+ this.express.use(bodyParser.urlencoded({ extended: false }));
+ }
- // Configure API endpoints.
- private mountRoutes (): void {
- const defRouter = express.Router()
- defRouter.get('/', (req, res) => {
- res.json({
- message: 'Welcome to the CS3099 BE4 server!',
- important : 'Endpoints start from /cs3099group-be-4/'
- })
- })
- this.express.use('/', defRouter)
- this.express.use('/cs3099group-be-4', FileRouter)
- }
+ // Configure API endpoints.
+ private mountRoutes(): void {
+ const defRouter: ex.Router = ex.Router();
+ defRouter.get('/', (req: ex.Request, res: ex.Response): void => {
+ res.json({
+ message: 'Welcome to the CS3099 BE4 server!',
+ important : 'Endpoints start from /cs3099group-be-4/'
+ });
+ });
+ this.express.use('/', defRouter);
+ this.express.use('/cs3099group-be-4', FileRouter);
+ }
}
-export default new App().express
+export default new App().express;
diff --git a/src/db/initPostgresDB.ts b/src/db/initPostgresDB.ts
index 307d9b6..eb979f4 100644
--- a/src/db/initPostgresDB.ts
+++ b/src/db/initPostgresDB.ts
@@ -1,13 +1,15 @@
-var Sequelize = require('sequelize');
-const Op = Sequelize.Op;
-const gres = new Sequelize('postgres://admin:eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af@localhost:5432/be4',
- {operatorsAliases : false});
+import * as Sequelize from 'sequelize';
+const gres: Sequelize.Sequelize = new Sequelize(
+ 'postgres://admin:eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af@localhost:5432/be4',
+ {
+ operatorsAliases : false
+ }
+);
-gres
- .authenticate()
- .then(() => {
- console.log('Connection has been established successfully.');
- })
- .catch(err => {
- console.error('Unable to connect to the database:', err);
- });
+gres.authenticate()
+ .then(() => {
+ // Connection has been established successfully.
+ })
+ .catch((err: Error) => {
+ // Unable to connect to the database.
+ });
diff --git a/src/index.ts b/src/index.ts
index 69150e2..54ff848 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,14 +1,21 @@
+/* tslint:disable:no-console
+ * This only goes here until we have a logging system */
+
+import app from './app';
+
console.log('Welcome to the CS3099 Server thingy!');
-import app from './app'
+const DEFAULT_PORT: number = 3000;
-// use default port 3000 or port supplied by OS
-const port = process.env.PORT || 3000
+// Use default port 3000 or port supplied by OS
+const port: number = process.env.PORT
+ ? process.env.PORT
+ : DEFAULT_PORT;
-app.listen(port, (err) => {
- if (err) {
- return console.log(err)
- }
+app.listen(port, (err: Error): void => {
+ if (err) {
+ return console.log(err);
+ }
- return console.log(`server is listening on port ${port}`)
-}) \ No newline at end of file
+ return console.log(`server is listening on port ${port}`);
+});
diff --git a/src/serverConfig.ts b/src/serverConfig.ts
index 1ef7c83..9e75085 100644
--- a/src/serverConfig.ts
+++ b/src/serverConfig.ts
@@ -1,89 +1,118 @@
-var serverConfig : Property[] = [];
+const serverConfig: Property[] = [];
/**
* A way to display user-configurable properties.
*/
class PropertyDisplay {
- /**
- * Constructs a [[PropertyDisplay]] using its properties.
- *
- * @param cat The property's category.
- * @param grp The property's group.
- * @param dn The property's displayable name.
- * @param desc A description of the property.
- */
- constructor(cat : string, grp : string, dn : string, desc : string) {
- this.category = cat;
- this.group = grp;
- this.display_name = dn;
- this.description = desc;
- };
-
- /**
- * The category the property belongs to.
- */
- category : string;
-
- /**
- * The group the property belongs to.
- */
- group : string;
-
- /**
- * The name for the property to display to a user.
- */
- display_name : string;
-
- /**
- * The description of the property.
- */
- description : string;
-};
+ /**
+ * The category the property belongs to.
+ */
+ public category: string;
+
+ /**
+ * The group the property belongs to.
+ */
+ public group: string;
+
+ /**
+ * The name for the property to display to a user.
+ */
+ public displayName: string;
+
+ /**
+ * The description of the property.
+ */
+ public description: string;
+
+ /**
+ * Constructs a [[PropertyDisplay]] using its properties.
+ *
+ * @param cat The property's category.
+ * @param grp The property's group.
+ * @param dn The property's displayable name.
+ * @param desc A description of the property.
+ */
+ public constructor(cat: string, grp: string, dn: string, desc: string) {
+ this.category = cat;
+ this.group = grp;
+ this.displayName = dn;
+ this.description = desc;
+ }
+}
-/* This is a class used to contain all of the protocol attributes of a Property
- of the current backend server.*/
/**
* A server property that infuences the running of the server.
* Loaded from configs at launch, and possibly editable during run-time.
*/
-class Property {
- /**
- * The property's unique ID.
- */
- id : string;
-
- /**
- * How to display the property to the user.
- */
- display? : PropertyDisplay;
-
- /**
- * Is the property read-only, or can it be edited at run-time?
- */
- read_only : boolean;
-
- /**
- * The variable type of the property.
- *
- * These strings represent Javascript types directly,
- * except `"integer"`, which is a `number` in logic.
- */
- type : "string" | "number" | "integer" | "boolean";
-
- /**
- * The value of the property.
- */
- value : string | number | boolean;
+interface Property {
+ /**
+ * The property's unique ID.
+ */
+ id: string;
+
+ /**
+ * How to display the property to the user.
+ */
+ display?: PropertyDisplay;
+
+ /**
+ * Is the property read-only, or can it be edited at run-time?
+ */
+ readOnly: boolean;
+
+ /**
+ * The variable type of the property.
+ *
+ * These strings represent Javascript types directly,
+ * except `"integer"`, which is a `number` in logic.
+ */
+ type: 'string' | 'number' | 'integer' | 'boolean';
+
+ /**
+ * The value of the property.
+ */
+ value: string | number | boolean;
}
-var property_display = new PropertyDisplay("Logging", "BE4", "Is logging enabled?", "This property defines if logging is currently enabled on this backend server.");
-serverConfig.push({id : "Server_Log", display : property_display, read_only : false, type : "boolean", value : false});
+// Logging
+let propertyDisplay: PropertyDisplay = new PropertyDisplay(
+ 'Logging',
+ 'BE4',
+ 'Is logging enabled?',
+ 'This property defines if logging is currently enabled on this backend server.'
+);
+
+serverConfig.push({
+ id: 'Server_Log',
+ display: propertyDisplay,
+ readOnly: false,
+ type: 'boolean',
+ value: false
+});
+
+// Caching Settings (global)
+serverConfig.push({
+ id: 'Global_Cache_Limit',
+ readOnly: true,
+ type: 'integer',
+ value: 1
+});
-//caching settings (global)
-serverConfig.push({id : "Global_Cache_Limit", read_only : true, type : "integer", value : 1});
-//caching settings (project level)
-property_display = new PropertyDisplay("Caching", "BE4", "Caching Type", "This property defines the current caching style for this project.");
-serverConfig.push({id : "project_example", display : property_display, read_only : false, type : "integer", value : 1});
+// Caching Settings (project level)
+propertyDisplay = new PropertyDisplay(
+ 'Caching',
+ 'BE4',
+ 'Caching Type',
+ 'This property defines the current caching style for this project.'
+);
+
+serverConfig.push({
+ id: 'project_example',
+ display: propertyDisplay,
+ readOnly: false,
+ type: 'integer',
+ value: 1
+});
/**
* Checks if a property exists in the server's property list.
@@ -92,18 +121,16 @@ serverConfig.push({id : "project_example", display : property_display, read_only
* @returns The index of the property in the server's property list,
* or `-1` if the property is not present.
*/
-function propertyExists (propKey : string): number {
- var found = -1;
- for (var prop in serverConfig) {
- if (serverConfig[prop].id == propKey) {
- found = parseInt(prop);
- break;
- }
- }
- return found;
-}
+export const propertyExists: (propKey: string) => number =
+ (propKey: string): number => {
+ let found: number = -1;
+ for (const prop in serverConfig) {
+ if (serverConfig[prop].id === propKey) {
+ found = parseInt(prop, 10);
+ break;
+ }
+ }
+ return found;
+};
-module.exports = {
- default : serverConfig,
- propertyExists : propertyExists,
-}
+export default serverConfig;
diff --git a/tsconfig.json b/tsconfig.json
index 745ef12..fbab410 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -5,7 +5,8 @@
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"module": "commonjs",
/* Where to output .js files */
- "outDir": "dist"
+ "outDir": "dist",
+ "strict": true
},
/* Where to look for .ts files */
"include": [
diff --git a/tslint.json b/tslint.json
new file mode 100644
index 0000000..f86eb35
--- /dev/null
+++ b/tslint.json
@@ -0,0 +1,302 @@
+{
+ "defaultSeverity": "error",
+ "extends": [],
+ "jsRules": {},
+ "rules": {
+ "adjacent-overload-signatures": true,
+ "ban-types": [false],
+ "member-access": [
+ true,
+ "check-accessor",
+ "check-constructor",
+ "check-parameter-property"
+ ],
+ "member-ordering": [
+ true,
+ {
+ "order": [
+ "static-field",
+ "static-method",
+ "instance-field",
+ "constructor",
+ "instance-method"
+ ]
+ }
+ ],
+ "no-any": true,
+ "no-empty-interface": false,
+ "no-import-side-effect": true,
+ "no-inferrable-types": false,
+ "no-internal-module": true,
+ "no-magic-numbers": false,
+ "no-namespace": true,
+ "no-non-null-assertion": true,
+ "no-parameter-reassignment": true,
+ "no-reference": true,
+ "no-unnecessary-type-assertion": {},
+ "no-var-requires": true,
+ "only-arrow-functions": true,
+ "prefer-for-of": true,
+ "promise-function-async": true,
+ "typedef": [
+ true,
+ "call-signature",
+ "arrow-call-signature",
+ "parameter",
+ "arrow-parameter",
+ "property-declaration",
+ "variable-declaration",
+ "member-variable-declaration",
+ "object-destructuring",
+ "array-destructuring"
+ ],
+ "typedef-whitespace": [
+ true,
+ {
+ "call-signature": "nospace",
+ "index-signature": "nospace",
+ "parameter": "nospace",
+ "property-declaration": "nospace",
+ "variable-declaration": "nospace"
+ },
+ {
+ "call-signature": "onespace",
+ "index-signature": "onespace",
+ "parameter": "onespace",
+ "property-decalaration": "onespace",
+ "variable-declaration": "onespace"
+ }
+ ],
+ "unified-signatures": true,
+
+ "await-promise": true,
+ "ban-comma-operator": true,
+ "ban": [ false ],
+ "curly": true,
+ "forin": true,
+ "import-blacklist": [],
+ "label-position": true,
+ "no-arg": true,
+ "no-bitwise": true,
+ "no-conditional-assignment": true,
+ "no-console": [ true ],
+ "no-construct": true,
+ "no-debugger": true,
+ "no-duplicate-super": true,
+ "no-duplicate-switch-case": true,
+ "no-duplicate-variable": true,
+ "no-dynamic-delete": true,
+ "no-empty": true,
+ "no-eval": true,
+ "no-floating-promises": true,
+ "no-for-in-array": false,
+ "no-implicit-dependencies": true,
+ "no-inferred-empty-object-type": true,
+ "no-invalid-template-strings": true,
+ "no-invalid-this": true,
+ "no-misused-new": true,
+ "no-null-keyword": false,
+ "no-object-literal-type-assertion": true,
+ "no-return-await": true,
+ "no-shadowed-variable": true,
+ "no-sparse-arrays": true,
+ "no-string-literal": true,
+ "no-string-throw": true,
+ "no-submodule-imports": false,
+ "no-switch-case-fall-through": true,
+ "no-this-assignment": [
+ true,
+ "allow-destructuring"
+ ],
+ "no-unbound-method": true,
+ "no-unnecessary-class": true,
+ "no-unsafe-any": false,
+ "no-unsafe-finally": true,
+ "no-unused-expression": true,
+ "no-unused-variable": true,
+ "no-use-before-declare": true,
+ "no-var-keyword": true,
+ "no-void-expression": false,
+ "prefer-conditional-expression": true,
+ "prefer-object-spread": true,
+ "radix": true,
+ "restrict-plus-operands": true,
+ "strict-boolean-expressions": false,
+ "strict-type-predicates": true,
+ "switch-default": false,
+ "triple-equals": [
+ true,
+ "allow-null-check"
+ ],
+ "use-default-type-parameter": true,
+ "use-isnan": true,
+
+ "cyclomatic-complexity": [
+ true,
+ 20
+ ],
+ "deprecation": true,
+ "eofline": true,
+ "indent": [
+ true,
+ "tabs",
+ 4
+ ],
+ "linebreak-style": [
+ true,
+ "LF"
+ ],
+ "max-classes-per-file": [
+ true,
+ 1
+ ],
+ "max-file-line-count": [ false ],
+ "max-line-length": [
+ true,
+ 80
+ ],
+ "no-default-export": false,
+ "no-duplicate-imports": true,
+ "no-mergeable-namespace": true,
+ "no-require-imports": true,
+ "object-literal-sort-keys": false,
+ "prefer-const": true,
+ "prefer-readonly": true,
+ "trailing-comma": [
+ true,
+ {
+ "multiline": "never",
+ "singleline": "never"
+ }
+ ],
+
+ "align": [
+ true,
+ "parameters",
+ "arguments",
+ "statements",
+ "members",
+ "elements"
+ ],
+ "array-type": [
+ true,
+ "array"
+ ],
+ "arrow-parens": true,
+ "arrow-return-shorthand": true,
+ "binary-expression-operand-order": true,
+ "callable-types": true,
+ "class-name": true,
+ "comment-format": [
+ true,
+ "check-space",
+ "check-uppercase"
+ ],
+ "completed-docs": [
+ false,
+ "classes",
+ "enums",
+ "enum-members",
+ "functions",
+ "interfaces",
+ "methods",
+ "namespaces",
+ "properties",
+ "types"
+ ],
+ "encoding": true,
+ "file-header": [ false ],
+ "import-spacing": true,
+ "interface-name": false,
+ "interface-over-type-literal": true,
+ "jsdoc-format": [
+ true,
+ "check-multiline-start"
+ ],
+ "match-default-export-name": false,
+ "newline-before-return": false,
+ "newline-per-chained-call": true,
+ "new-parens": true,
+ "no-angle-bracket-type-assertion": true,
+ "no-boolean-literal-compare": true,
+ "no-consecutive-blank-lines": [
+ true,
+ 1
+ ],
+ "no-irregular-whitespace": true,
+ "no-parameter-properties": true,
+ "no-redundant-jsdoc": true,
+ "no-reference-import": true,
+ "no-trailing-whitespace": true,
+ "no-unnecessary-callback-wrapper": true,
+ "no-unnecessary-qualifier": true,
+ "number-literal-format": true,
+ "object-literal-key-quotes": [
+ true,
+ "as-needed"
+ ],
+ "object-literal-shorthand": true,
+ "one-line": [
+ true,
+ "check-catch",
+ "check-finally",
+ "check-else",
+ "check-open-brace",
+ "check-whitespace"
+ ],
+ "one-variable-per-declaration": true,
+ "ordered-imports": [
+ true,
+ {
+ "import-sources-order": "case-insensitive",
+ "grouped-imports": true,
+ "named-imports-order": "lowercase-last",
+ "module-source-path": "basename"
+ }
+ ],
+ "prefer-function-over-method": true,
+ "prefer-switch": [
+ true,
+ {
+ "min-cases": 2
+ }
+ ],
+ "prefer-template": true,
+ "quotemark": [
+ true,
+ "single",
+ "jsx-single",
+ "avoid-template",
+ "avoid-escape"
+ ],
+ "return-undefined": true,
+ "semicolon": true,
+ "space-before-function-paren": [
+ true,
+ "never"
+ ],
+ "switch-final-break": [
+ true,
+ "always"
+ ],
+ "type-literal-delimiter": true,
+ "variable-name": [
+ true,
+ "check-format"
+ ],
+ "whitespace": [
+ true,
+ "check-branch",
+ "check-decl",
+ "check-operator",
+ "check-module",
+ "check-separator",
+ "check-rest-spread",
+ "check-type",
+ "check-typecast",
+ "check-type-operator",
+ "check-preblock"
+ ]
+ },
+ "rulesDirectory": []
+}