This commit is contained in:
Amaury 2021-05-19 12:55:10 +02:00
commit 2c67212790
15 changed files with 412 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
build/
.vscode/

19
LICENSE Normal file
View File

@ -0,0 +1,19 @@
MIT License Copyright (c) <year> <copyright holders>
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 (including the next
paragraph) 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.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# Discord

0
package-lock.json generated Normal file
View File

53
package.json Normal file
View File

@ -0,0 +1,53 @@
{
"name": "discord",
"version": "1.0.0",
"description": "",
"main": "build/index.js",
"types": "build/index.d.ts",
"directories": {
"test": "tests"
},
"scripts": {
"build": "tsc -p .",
"test": "env TS_NODE_PROJECT='./tests/tsconfig.json' mocha --require ts-node/register ./tests/**/*-spec.ts",
"lint": "eslint 'tests/**/*.ts' 'src/**/*.ts'"
},
"repository": {
"type": "git",
"url": "https://zeteo.me/gitea/amaury.joly/Discord.git"
},
"keywords": [
"Discord",
"listener-rss"
],
"author": "Amaury JOLY",
"license": "MIT",
"_id": "discord@1.0.0",
"dependencies": {
"@types/chai": "^4.2.18",
"@types/mocha": "^8.2.2",
"@types/node": "^15.3.0",
"@types/sinon-chai": "^3.2.5",
"@typescript-eslint/eslint-plugin": "^4.23.0",
"@typescript-eslint/parser": "^4.23.0",
"chai": "^4.3.4",
"discord.js": "^12.5.3",
"eslint": "^7.26.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.23.2",
"eslint-plugin-mocha": "^8.1.0",
"eslint-plugin-prettier": "^3.4.0",
"mocha": "^8.4.0",
"prettier": "^2.3.0",
"sinon-chai": "^3.6.0",
"tmp-promise": "^3.0.2",
"ts-node": "^9.1.1",
"ts-sinon": "^2.0.1",
"tsc-watch": "^4.2.9",
"typescript": "^4.2.4"
},
"devDependencies": {
"@types/ws": "^7.4.4"
}
}

5
src/implementableApi.ts Normal file
View File

@ -0,0 +1,5 @@
import EventEmitter from "events";
export class ImplementableApi extends EventEmitter {
}

4
src/index.ts Normal file
View File

@ -0,0 +1,4 @@
// export * as Router from "./router"
export {Router} from "./router"
export {ImplementableApi} from "./implementableApi"

40
src/router.ts Normal file
View File

@ -0,0 +1,40 @@
import { ImplementableApi } from "./implementableApi";
namespace Router {
export type Config = {
events: {
"name": string,
"type": 0 | 1
}[];
routes: {
"serviceName": string,
"eventAccepted": string[] | undefined,
"eventEmitted": string[] | undefined
}[]
}
}
class Router {
api_array: ImplementableApi[] = [];
config: Router.Config;
constructor(readonly path: string) {
const tmp_config: Router.Config = require(path);
this.config = tmp_config;
// if(tmp_config["events"] === )
}
public addApi<T extends ImplementableApi>(new_api: T) {
const new_api_conf = this.config.routes.find((elmt) => elmt.serviceName === new_api.constructor.name);
// test if fun exist
for(let ev in new_api_conf?.eventAccepted)
if(ev !in new_api)
throw new Error(`The class ${new_api.constructor.name} haven't the expected function`);
//test if events call exist
for(let ev in new_api_conf?.eventEmitted)
if(ev !in new_api.eventNames)
throw `The class ${new_api.constructor.name} haven't the well defined events`;
}
}
export { Router };

2
tests/index-spec.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=index-spec.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index-spec.d.ts","sourceRoot":"","sources":["index-spec.ts"],"names":[],"mappings":""}

116
tests/index-spec.js Normal file
View File

@ -0,0 +1,116 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var chai_1 = __importDefault(require("chai"));
var ts_sinon_1 = __importDefault(require("ts-sinon"));
var sinon_chai_1 = __importDefault(require("sinon-chai"));
chai_1.default.use(sinon_chai_1.default);
var expect = chai_1.default.expect;
var tmp_promise_1 = require("tmp-promise");
var fs_1 = require("fs");
var index_1 = require("../src/index");
var path = require("path");
var well_build_routing_file = require(path.join(__dirname, "rsrc/wellBuildedRoutingFile.json"));
describe("testing the routing part", function () {
describe("testing the building part", function () {
it("it will test the constructor with a well format config file", function () {
//given
var fun = function () {
var r = new index_1.Router(path.join(__dirname, "rsrc/wellBuildedRoutingFile.json"));
};
var spy = ts_sinon_1.default.spy(fun);
// when
try {
spy();
}
catch (error) {
// nothing it's a test
}
// assert
expect(spy).to.not.thrown();
});
it("it will test a bad formed file", function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, tmp_promise_1.withFile(function (file) { return __awaiter(_this, void 0, void 0, function () {
var fun, spy;
return __generator(this, function (_a) {
//given
fs_1.writeFileSync(file.path, JSON.stringify(__assign(__assign({}, well_build_routing_file), { events: 12 })));
fun = function () {
var r = new index_1.Router(file.path);
console.log(r.config);
};
spy = ts_sinon_1.default.spy(fun);
// when
try {
spy();
}
catch (error) {
// nothing it's a test
}
// assert
expect(spy).to.not.thrown();
return [2 /*return*/];
});
}); }, { postfix: ".json" })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
});
});
});

59
tests/index-spec.ts Normal file
View File

@ -0,0 +1,59 @@
import chai from "chai";
import sinon from "ts-sinon";
import sinonChai from "sinon-chai";
chai.use(sinonChai)
const expect = chai.expect;
import { withFile } from "tmp-promise"
import { writeFileSync } from "fs";
import { Router } from "../src/index";
const path = require("path");
const well_build_routing_file: Router.Config = require(path.join(__dirname, "rsrc/wellBuildedRoutingFile.json"));
describe("testing the routing part", function () {
describe("testing the building part", function () {
it("it will test the constructor with a well format config file", function () {
//given
const fun = () => {
const r = new Router(path.join(__dirname, "rsrc/wellBuildedRoutingFile.json"));
};
const spy = sinon.spy(fun);
// when
try {
spy();
} catch (error) {
// nothing it's a test
}
// assert
expect(spy).to.not.thrown();
})
it("it will test a bad formed file", async function () {
await withFile(async (file) => {
//given
writeFileSync(file.path, JSON.stringify({...well_build_routing_file, ...{events: 12}}));
const fun = () => {
const r = new Router(file.path);
console.log(r.config);
};
const spy = sinon.spy(fun);
// when
try {
spy();
} catch (error) {
// nothing it's a test
}
// assert
expect(spy).to.not.thrown();
}, {postfix: ".json"});
})
})
});

View File

@ -0,0 +1,35 @@
{
"events": [
{
"name": "newEntriesNotify",
"type": 0
},
{
"name": "uploadRequest",
"type": 0
},
{
"name": "newListenerRequest",
"type": 0
},
{
"name": "removeListenerRequest",
"type": 0
}
],
"routes": [
{
"serviceName": "Discord",
"eventAccepted": ["newEntriesNotify"],
"eventEmitted": ["uploadRequest", "newListenerRequest", "removeListenerRequest"]
},
{
"serviceName": "logWriter",
"eventAccepted": []
},
{
"serviceName": "peertubeRequester",
"eventAccepted": ["uploadRequest"]
}
]
}

4
tests/tsconfig.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "../tsconfig.json",
"include": ["./"]
}

69
tsconfig.json Normal file
View File

@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build/", /* Redirect output structure to the directory. */
"rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"./src"
],
}