mirror of
https://github.com/codex-team/codex.docs.git
synced 2025-08-08 06:55:26 +02:00
Removed compiled js files, eslint codex/ts added
This commit is contained in:
parent
51450f4d9f
commit
1f166c1a3d
81 changed files with 514 additions and 5244 deletions
|
@ -1,5 +1,6 @@
|
|||
{
|
||||
"extends": [
|
||||
"codex/ts",
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/eslint-recommended",
|
||||
"plugin:@typescript-eslint/recommended"
|
||||
|
@ -14,7 +15,8 @@
|
|||
"rules": {
|
||||
"no-unused-expressions": 0,
|
||||
"chai-friendly/no-unused-expressions": 2,
|
||||
"@typescript-eslint/ban-types": 1
|
||||
"@typescript-eslint/ban-types": 1,
|
||||
"@typescript-eslint/no-magic-numbers": 0
|
||||
},
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"globals": {
|
||||
|
|
|
@ -33,6 +33,10 @@ $ yarn install --frozen-lockfile
|
|||
```
|
||||
|
||||
### Available scripts
|
||||
#### Compile to Javascript
|
||||
```
|
||||
$ yarn compile
|
||||
```
|
||||
|
||||
#### Start the server
|
||||
|
||||
|
|
|
@ -1,82 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
const app_1 = __importDefault(require("../src/app"));
|
||||
const http_1 = __importDefault(require("http"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const debug = debug_1.default.debug("codex.editor.docs:server");
|
||||
/**
|
||||
* Get port from environment and store in Express.
|
||||
*/
|
||||
const port = normalizePort(config_1.default.get("port") || '3000');
|
||||
app_1.default.set('port', port);
|
||||
/**
|
||||
* Create HTTP server.
|
||||
*/
|
||||
const server = http_1.default.createServer(app_1.default);
|
||||
/**
|
||||
* Listen on provided port, on all network interfaces.
|
||||
*/
|
||||
server.listen(port);
|
||||
server.on('error', onError);
|
||||
server.on('listening', onListening);
|
||||
/**
|
||||
* Normalize a port into a number, string, or false.
|
||||
*/
|
||||
function normalizePort(val) {
|
||||
const value = parseInt(val, 10);
|
||||
if (isNaN(value)) {
|
||||
// named pipe
|
||||
return val;
|
||||
}
|
||||
if (value >= 0) {
|
||||
// port number
|
||||
return value;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Event listener for HTTP server "error" event.
|
||||
*/
|
||||
function onError(error) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
}
|
||||
const bind = typeof port === 'string'
|
||||
? 'Pipe ' + port
|
||||
: 'Port ' + port;
|
||||
// handle specific listen errors with friendly messages
|
||||
switch (error.code) {
|
||||
case 'EACCES':
|
||||
console.error(bind + ' requires elevated privileges');
|
||||
process.exit(1);
|
||||
break;
|
||||
case 'EADDRINUSE':
|
||||
console.error(bind + ' is already in use');
|
||||
process.exit(1);
|
||||
break;
|
||||
default:
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Event listener for HTTP server "listening" event.
|
||||
*/
|
||||
function onListening() {
|
||||
const addr = server.address();
|
||||
if (addr === null) {
|
||||
debug('Address not found');
|
||||
process.exit(1);
|
||||
}
|
||||
const bind = typeof addr === 'string'
|
||||
? 'pipe ' + addr
|
||||
: 'port ' + addr.port;
|
||||
debug('Listening on ' + bind);
|
||||
}
|
||||
exports.default = { server, app: app_1.default };
|
|
@ -1,54 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const database_1 = __importDefault(require("./src/utils/database"));
|
||||
let db = database_1.default['password'];
|
||||
const commander_1 = __importDefault(require("commander"));
|
||||
const program = commander_1.default.program;
|
||||
const bcrypt_1 = __importDefault(require("bcrypt"));
|
||||
const saltRounds = 12;
|
||||
/**
|
||||
* Script for generating password, that will be used to create and edit pages in CodeX.Docs.
|
||||
* Hashes password with bcrypt and inserts it to the database.
|
||||
* @see {https://github.com/tj/commander.js | CommanderJS}
|
||||
*/
|
||||
program
|
||||
.description('Application for generating password, that will be used to create and edit pages in CodeX.Docs.')
|
||||
.usage('[password]')
|
||||
.arguments('<password>')
|
||||
.action(function (password) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
bcrypt_1.default.hash(password, saltRounds, (error, hash) => __awaiter(this, void 0, void 0, function* () {
|
||||
if (error) {
|
||||
return 'Hash generating error';
|
||||
}
|
||||
const userDoc = { passHash: hash };
|
||||
yield db.remove({}, { multi: true });
|
||||
yield db.insert(userDoc);
|
||||
console.log('Password was successfully generated');
|
||||
}));
|
||||
});
|
||||
});
|
||||
program.on('--help', () => {
|
||||
console.log('');
|
||||
console.log('Example:');
|
||||
console.log('yarn generatePassword qwerty');
|
||||
console.log('');
|
||||
});
|
||||
program.parse(process.argv);
|
||||
if (process.argv.length !== 3) {
|
||||
console.error('Invalid command: %s\nSee --help or -h for a list of available commands.', program.args.join(' '));
|
||||
process.exit(1);
|
||||
}
|
13
package.json
13
package.json
|
@ -10,16 +10,17 @@
|
|||
],
|
||||
"scripts": {
|
||||
"start": "cross-env NODE_ENV=production nodemon --config nodemon.json ./bin/server.js",
|
||||
"start:ts": "cross-env NODE_ENV=production nodemon --config nodemon.json ./bin/server.ts",
|
||||
"start:dev": "cross-env NODE_ENV=development nodemon --config nodemon.json ./bin/server.ts",
|
||||
"test": "cross-env NODE_ENV=testing mocha --recursive ./test",
|
||||
"test": "cross-env NODE_ENV=testing mocha --recursive ./test --exit",
|
||||
"test:ts": "cross-env NODE_ENV=testing ts-mocha ./test/*.ts ./test/**/*.ts --exit",
|
||||
"lint": "eslint --fix --cache --ext .ts ./src",
|
||||
"build": "webpack ./src/frontend/js/app.js --o='./public/dist/[name].bundle.js' --output-library=Docs --output-public-path=/dist/ -p --mode=production",
|
||||
"build:dev": "webpack ./src/frontend/js/app.js --o='./public/dist/[name].bundle.js' --output-library=Docs --output-public-path=/dist/ -p --mode=development --watch",
|
||||
"precommit": "yarn lint && yarn test --exit",
|
||||
"generatePassword": "node ./generatePassword.js",
|
||||
"precommit": "yarn lint && yarn test:ts",
|
||||
"generatePassword": "ts-node ./generatePassword.ts",
|
||||
"editor-upgrade": "yarn add -D @editorjs/{editorjs,header,code,delimiter,list,link,image,table,inline-code,marker,warning,checklist,raw}@latest",
|
||||
"test:ts": "cross-env NODE_ENV=testing ts-mocha --recursive ./test",
|
||||
"build:ts": "npx tsc"
|
||||
"compile": "npx tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.0.1",
|
||||
|
@ -42,6 +43,7 @@
|
|||
"node-fetch": "^2.6.1",
|
||||
"nodemon": "^2.0.12",
|
||||
"open-graph-scraper": "^4.9.0",
|
||||
"ts-node": "^10.1.0",
|
||||
"twig": "^1.15.4",
|
||||
"typescript-eslint": "^0.0.1-alpha.0",
|
||||
"uuid4": "^2.0.2"
|
||||
|
@ -128,7 +130,6 @@
|
|||
"rimraf": "^3.0.2",
|
||||
"sinon": "^11.1.2",
|
||||
"ts-mocha": "^8.0.0",
|
||||
"ts-node": "^10.1.0",
|
||||
"typescript": "^4.3.5",
|
||||
"webpack": "^4.17.1",
|
||||
"webpack-cli": "^3.1.0"
|
||||
|
|
34
src/app.js
34
src/app.js
|
@ -1,34 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const cookie_parser_1 = __importDefault(require("cookie-parser"));
|
||||
const morgan_1 = __importDefault(require("morgan"));
|
||||
const rcparser_1 = __importDefault(require("./utils/rcparser"));
|
||||
const routes_1 = __importDefault(require("./routes"));
|
||||
const app = express_1.default();
|
||||
const config = rcparser_1.default.getConfiguration();
|
||||
app.locals.config = config;
|
||||
// view engine setup
|
||||
app.set('views', path_1.default.join(__dirname, 'views'));
|
||||
app.set('view engine', 'twig');
|
||||
require('./utils/twig');
|
||||
app.use(morgan_1.default('dev'));
|
||||
app.use(express_1.default.json());
|
||||
app.use(express_1.default.urlencoded({ extended: true }));
|
||||
app.use(cookie_parser_1.default());
|
||||
app.use(express_1.default.static(path_1.default.join(__dirname, '../public')));
|
||||
app.use('/', routes_1.default);
|
||||
// error handler
|
||||
app.use(function (err, req, res, next) {
|
||||
// set locals, only providing error in development
|
||||
res.locals.message = err.message;
|
||||
res.locals.error = req.app.get('env') == 'development' ? err : {};
|
||||
// render the error page
|
||||
res.status(err.status || 500);
|
||||
res.render('error');
|
||||
});
|
||||
exports.default = app;
|
14
src/app.ts
14
src/app.ts
|
@ -1,10 +1,10 @@
|
|||
import express, { NextFunction, Request, Response } from "express";
|
||||
import path from "path";
|
||||
import cookieParser from "cookie-parser";
|
||||
import morgan from "morgan";
|
||||
import rcParser from "./utils/rcparser";
|
||||
import routes from "./routes";
|
||||
import HttpException from "./exceptions/httpException";
|
||||
import express, { NextFunction, Request, Response } from 'express';
|
||||
import path from 'path';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import morgan from 'morgan';
|
||||
import rcParser from './utils/rcparser';
|
||||
import routes from './routes';
|
||||
import HttpException from './exceptions/httpException';
|
||||
|
||||
const app = express();
|
||||
const config = rcParser.getConfiguration();
|
||||
|
|
|
@ -1,37 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const alias_1 = __importDefault(require("../models/alias"));
|
||||
/**
|
||||
* @class Aliases
|
||||
* @classdesc Aliases controller
|
||||
*/
|
||||
class Aliases {
|
||||
/**
|
||||
* Find and return entity with given alias
|
||||
*
|
||||
* @param {string} aliasName - alias name of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static get(aliasName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const alias = yield alias_1.default.get(aliasName);
|
||||
if (!alias.id) {
|
||||
throw new Error('Entity with given alias does not exist');
|
||||
}
|
||||
return alias;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = Aliases;
|
|
@ -11,7 +11,7 @@ class Aliases {
|
|||
* @param {string} aliasName - alias name of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static async get(aliasName: string): Promise<Alias> {
|
||||
public static async get(aliasName: string): Promise<Alias> {
|
||||
const alias = await Alias.get(aliasName);
|
||||
|
||||
if (!alias.id) {
|
||||
|
|
|
@ -1,192 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const page_1 = __importDefault(require("../models/page"));
|
||||
const page_2 = __importDefault(require("../models/page"));
|
||||
const alias_1 = __importDefault(require("../models/alias"));
|
||||
/**
|
||||
* @class Pages
|
||||
* @classdesc Pages controller
|
||||
*/
|
||||
class Pages {
|
||||
/**
|
||||
* Fields required for page model creation
|
||||
*
|
||||
* @returns {['title', 'body']}
|
||||
*/
|
||||
static get REQUIRED_FIELDS() {
|
||||
return ['body'];
|
||||
}
|
||||
/**
|
||||
* Find and return page model with passed id
|
||||
*
|
||||
* @param {string} id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static get(id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const page = yield page_1.default.get(id);
|
||||
if (!page._id) {
|
||||
throw new Error('Page with given id does not exist');
|
||||
}
|
||||
return page;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return all pages
|
||||
*
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static getAll() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return page_1.default.getAll();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return all pages without children of passed page
|
||||
*
|
||||
* @param {string} parent - id of current page
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static getAllExceptChildren(parent) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const pagesAvailable = this.removeChildren(yield Pages.getAll(), parent);
|
||||
const nullfilteredpages = [];
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
pagesAvailable.forEach((item, _index) => __awaiter(this, void 0, void 0, function* () {
|
||||
if (item instanceof page_2.default) {
|
||||
nullfilteredpages.push(item);
|
||||
}
|
||||
}));
|
||||
return nullfilteredpages;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Set all children elements to null
|
||||
*
|
||||
* @param {Array<Page|null>} [pagesAvailable] - Array of all pages
|
||||
* @param {string} parent - id of parent page
|
||||
* @returns {Array<?Page>}
|
||||
*/
|
||||
static removeChildren(pagesAvailable, parent) {
|
||||
pagesAvailable.forEach((item, index) => __awaiter(this, void 0, void 0, function* () {
|
||||
if (item === null || item._parent !== parent) {
|
||||
return;
|
||||
}
|
||||
pagesAvailable[index] = null;
|
||||
pagesAvailable = Pages.removeChildren(pagesAvailable, item._id);
|
||||
}));
|
||||
return pagesAvailable;
|
||||
}
|
||||
/**
|
||||
* Create new page model and save it in the database
|
||||
*
|
||||
* @param {PageData} data
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static insert(data) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
Pages.validate(data);
|
||||
const page = new page_1.default(data);
|
||||
const insertedPage = yield page.save();
|
||||
if (insertedPage.uri) {
|
||||
const alias = new alias_1.default({
|
||||
id: insertedPage._id,
|
||||
type: alias_1.default.types.PAGE,
|
||||
}, insertedPage.uri);
|
||||
alias.save();
|
||||
}
|
||||
return insertedPage;
|
||||
}
|
||||
catch (validationError) {
|
||||
throw new Error(validationError);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check PageData object for required fields
|
||||
*
|
||||
* @param {PageData} data
|
||||
* @throws {Error} - validation error
|
||||
*/
|
||||
static validate(data) {
|
||||
const allRequiredFields = Pages.REQUIRED_FIELDS.every(field => typeof data[field] !== 'undefined');
|
||||
if (!allRequiredFields) {
|
||||
throw new Error('Some of required fields is missed');
|
||||
}
|
||||
const hasBlocks = data.body && data.body.blocks && Array.isArray(data.body.blocks) && data.body.blocks.length > 0;
|
||||
if (!hasBlocks) {
|
||||
throw new Error('Page body is invalid');
|
||||
}
|
||||
const hasHeaderAsFirstBlock = data.body.blocks[0].type === 'header';
|
||||
if (!hasHeaderAsFirstBlock) {
|
||||
throw new Error('First page Block must be a Header');
|
||||
}
|
||||
const headerIsNotEmpty = data.body.blocks[0].data.text.replace('<br>', '').trim() !== '';
|
||||
if (!headerIsNotEmpty) {
|
||||
throw new Error('Please, fill page Header');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Update page with given id in the database
|
||||
*
|
||||
* @param {string} id - page id
|
||||
* @param {PageData} data
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static update(id, data) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const page = yield page_1.default.get(id);
|
||||
const previousUri = page.uri;
|
||||
if (!page._id) {
|
||||
throw new Error('Page with given id does not exist');
|
||||
}
|
||||
if (data.uri && !data.uri.match(/^[a-z0-9'-]+$/i)) {
|
||||
throw new Error('Uri has unexpected characters');
|
||||
}
|
||||
page.data = data;
|
||||
const updatedPage = yield page.save();
|
||||
if (updatedPage.uri !== previousUri) {
|
||||
if (updatedPage.uri) {
|
||||
const alias = new alias_1.default({
|
||||
id: updatedPage._id,
|
||||
type: alias_1.default.types.PAGE,
|
||||
}, updatedPage.uri);
|
||||
alias.save();
|
||||
}
|
||||
alias_1.default.markAsDeprecated(previousUri);
|
||||
}
|
||||
return updatedPage;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Remove page with given id from the database
|
||||
*
|
||||
* @param {string} id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static remove(id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const page = yield page_1.default.get(id);
|
||||
if (!page._id) {
|
||||
throw new Error('Page with given id does not exist');
|
||||
}
|
||||
const alias = yield alias_1.default.get(page.uri);
|
||||
yield alias.destroy();
|
||||
return page.destroy();
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = Pages;
|
|
@ -12,7 +12,7 @@ class Pages {
|
|||
*
|
||||
* @returns {['title', 'body']}
|
||||
*/
|
||||
static get REQUIRED_FIELDS(): Array<string> {
|
||||
public static get REQUIRED_FIELDS(): Array<string> {
|
||||
return [ 'body' ];
|
||||
}
|
||||
|
||||
|
@ -22,7 +22,7 @@ class Pages {
|
|||
* @param {string} id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async get(id: string): Promise<Page> {
|
||||
public static async get(id: string): Promise<Page> {
|
||||
const page = await Model.get(id);
|
||||
|
||||
if (!page._id) {
|
||||
|
@ -37,7 +37,7 @@ class Pages {
|
|||
*
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static async getAll(): Promise<Page[]> {
|
||||
public static async getAll(): Promise<Page[]> {
|
||||
return Model.getAll();
|
||||
}
|
||||
|
||||
|
@ -47,7 +47,7 @@ class Pages {
|
|||
* @param {string} parent - id of current page
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static async getAllExceptChildren(parent: string): Promise<Page[]> {
|
||||
public static async getAllExceptChildren(parent: string): Promise<Page[]> {
|
||||
const pagesAvailable = this.removeChildren(await Pages.getAll(), parent);
|
||||
|
||||
const nullfilteredpages: Page[] = [];
|
||||
|
@ -69,7 +69,7 @@ class Pages {
|
|||
* @param {string} parent - id of parent page
|
||||
* @returns {Array<?Page>}
|
||||
*/
|
||||
static removeChildren(pagesAvailable: Array<Page|null>, parent: string | undefined): Array<Page | null> {
|
||||
public static removeChildren(pagesAvailable: Array<Page|null>, parent: string | undefined): Array<Page | null> {
|
||||
pagesAvailable.forEach(async (item, index) => {
|
||||
if (item === null || item._parent !== parent) {
|
||||
return;
|
||||
|
@ -87,7 +87,7 @@ class Pages {
|
|||
* @param {PageData} data
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async insert(data: PageData): Promise<Page> {
|
||||
public static async insert(data: PageData): Promise<Page> {
|
||||
try {
|
||||
Pages.validate(data);
|
||||
|
||||
|
@ -110,38 +110,6 @@ class Pages {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check PageData object for required fields
|
||||
*
|
||||
* @param {PageData} data
|
||||
* @throws {Error} - validation error
|
||||
*/
|
||||
static validate(data: PageData): void {
|
||||
const allRequiredFields = Pages.REQUIRED_FIELDS.every(field => typeof data[field] !== 'undefined');
|
||||
|
||||
if (!allRequiredFields) {
|
||||
throw new Error('Some of required fields is missed');
|
||||
}
|
||||
|
||||
const hasBlocks = data.body && data.body.blocks && Array.isArray(data.body.blocks) && data.body.blocks.length > 0;
|
||||
|
||||
if (!hasBlocks) {
|
||||
throw new Error('Page body is invalid');
|
||||
}
|
||||
|
||||
const hasHeaderAsFirstBlock = data.body.blocks[0].type === 'header';
|
||||
|
||||
if (!hasHeaderAsFirstBlock) {
|
||||
throw new Error('First page Block must be a Header');
|
||||
}
|
||||
|
||||
const headerIsNotEmpty = data.body.blocks[0].data.text.replace('<br>', '').trim() !== '';
|
||||
|
||||
if (!headerIsNotEmpty) {
|
||||
throw new Error('Please, fill page Header');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update page with given id in the database
|
||||
*
|
||||
|
@ -149,7 +117,7 @@ class Pages {
|
|||
* @param {PageData} data
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async update(id: string, data: PageData): Promise<Page> {
|
||||
public static async update(id: string, data: PageData): Promise<Page> {
|
||||
const page = await Model.get(id);
|
||||
const previousUri = page.uri;
|
||||
|
||||
|
@ -186,7 +154,7 @@ class Pages {
|
|||
* @param {string} id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async remove(id: string): Promise<Page> {
|
||||
public static async remove(id: string): Promise<Page> {
|
||||
const page = await Model.get(id);
|
||||
|
||||
if (!page._id) {
|
||||
|
@ -199,6 +167,38 @@ class Pages {
|
|||
|
||||
return page.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check PageData object for required fields
|
||||
*
|
||||
* @param {PageData} data
|
||||
* @throws {Error} - validation error
|
||||
*/
|
||||
private static validate(data: PageData): void {
|
||||
const allRequiredFields = Pages.REQUIRED_FIELDS.every(field => typeof data[field] !== 'undefined');
|
||||
|
||||
if (!allRequiredFields) {
|
||||
throw new Error('Some of required fields is missed');
|
||||
}
|
||||
|
||||
const hasBlocks = data.body && data.body.blocks && Array.isArray(data.body.blocks) && data.body.blocks.length > 0;
|
||||
|
||||
if (!hasBlocks) {
|
||||
throw new Error('Page body is invalid');
|
||||
}
|
||||
|
||||
const hasHeaderAsFirstBlock = data.body.blocks[0].type === 'header';
|
||||
|
||||
if (!hasHeaderAsFirstBlock) {
|
||||
throw new Error('First page Block must be a Header');
|
||||
}
|
||||
|
||||
const headerIsNotEmpty = data.body.blocks[0].data.text.replace('<br>', '').trim() !== '';
|
||||
|
||||
if (!headerIsNotEmpty) {
|
||||
throw new Error('Please, fill page Header');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Pages;
|
||||
|
|
|
@ -1,133 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const pageOrder_1 = __importDefault(require("../models/pageOrder"));
|
||||
/**
|
||||
* @class PagesOrder
|
||||
* @classdesc PagesOrder controller
|
||||
*
|
||||
* Manipulates with Pages: changes the order, deletes, updates and so on...
|
||||
*/
|
||||
class PagesOrder {
|
||||
/**
|
||||
* Returns Page's order
|
||||
*
|
||||
* @param {string} parentId - of which page we want to get children order
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
static get(parentId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const order = yield pageOrder_1.default.get(parentId);
|
||||
if (!order._id) {
|
||||
throw new Error('Page with given id does not contain order');
|
||||
}
|
||||
return order;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns all records about page's order
|
||||
*
|
||||
* @returns {Promise<PageOrder[]>}
|
||||
*/
|
||||
static getAll() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return pageOrder_1.default.getAll();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Pushes the child page to the parent's order list
|
||||
*
|
||||
* @param {string} parentId - parent page's id
|
||||
* @param {string} childId - new page pushed to the order
|
||||
*/
|
||||
static push(parentId, childId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const order = yield pageOrder_1.default.get(parentId);
|
||||
order.push(childId);
|
||||
yield order.save();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Move one page to another Page's order
|
||||
*
|
||||
* @param {string} oldParentId - old parent page's id
|
||||
* @param {string} newParentId - new parent page's id
|
||||
* @param {string} targetPageId - page's id which is changing the parent page
|
||||
*/
|
||||
static move(oldParentId, newParentId, targetPageId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const oldParentOrder = yield pageOrder_1.default.get(oldParentId);
|
||||
oldParentOrder.remove(targetPageId);
|
||||
yield oldParentOrder.save();
|
||||
const newParentOrder = yield pageOrder_1.default.get(newParentId);
|
||||
newParentOrder.push(targetPageId);
|
||||
yield newParentOrder.save();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns new array with ordered pages
|
||||
*
|
||||
* @param {Page[]} pages - list of all available pages
|
||||
* @param {string} currentPageId - page's id around which we are ordering
|
||||
* @param {string} parentPageId - parent page's id that contains page above
|
||||
* @param {boolean} ignoreSelf - should we ignore current page in list or not
|
||||
* @returns {Page[]}
|
||||
*/
|
||||
static getOrderedChildren(pages, currentPageId, parentPageId, ignoreSelf = false) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const children = yield pageOrder_1.default.get(parentPageId);
|
||||
const unordered = pages.filter(page => page._parent === parentPageId).map(page => page._id);
|
||||
// Create unique array with ordered and unordered pages id
|
||||
const ordered = Array.from(new Set([...children.order, ...unordered]));
|
||||
const result = [];
|
||||
ordered.forEach(pageId => {
|
||||
pages.forEach(page => {
|
||||
if (page._id === pageId && (pageId !== currentPageId || !ignoreSelf)) {
|
||||
result.push(page);
|
||||
}
|
||||
});
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @param {string[]} unordered
|
||||
* @param {string} currentPageId - page's id that changes the order
|
||||
* @param {string} parentPageId - parent page's id that contains both two pages
|
||||
* @param {string} putAbovePageId - page's id above which we put the target page
|
||||
*/
|
||||
static update(unordered, currentPageId, parentPageId, putAbovePageId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const pageOrder = yield pageOrder_1.default.get(parentPageId);
|
||||
// Create unique array with ordered and unordered pages id
|
||||
pageOrder.order = Array.from(new Set([...pageOrder.order, ...unordered]));
|
||||
pageOrder.putAbove(currentPageId, putAbovePageId);
|
||||
yield pageOrder.save();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @param {string} parentId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static remove(parentId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const order = yield pageOrder_1.default.get(parentId);
|
||||
if (!order._id) {
|
||||
throw new Error('Page with given id does not contain order');
|
||||
}
|
||||
return order.destroy();
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = PagesOrder;
|
|
@ -15,7 +15,7 @@ class PagesOrder {
|
|||
* @param {string} parentId - of which page we want to get children order
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
static async get(parentId: string): Promise<PageOrder> {
|
||||
public static async get(parentId: string): Promise<PageOrder> {
|
||||
const order = await Model.get(parentId);
|
||||
|
||||
if (!order._id) {
|
||||
|
@ -30,7 +30,7 @@ class PagesOrder {
|
|||
*
|
||||
* @returns {Promise<PageOrder[]>}
|
||||
*/
|
||||
static async getAll(): Promise<PageOrder[]> {
|
||||
public static async getAll(): Promise<PageOrder[]> {
|
||||
return Model.getAll();
|
||||
}
|
||||
|
||||
|
@ -40,7 +40,7 @@ class PagesOrder {
|
|||
* @param {string} parentId - parent page's id
|
||||
* @param {string} childId - new page pushed to the order
|
||||
*/
|
||||
static async push(parentId: string, childId: string): Promise<void> {
|
||||
public static async push(parentId: string, childId: string): Promise<void> {
|
||||
const order = await Model.get(parentId);
|
||||
|
||||
order.push(childId);
|
||||
|
@ -54,7 +54,7 @@ class PagesOrder {
|
|||
* @param {string} newParentId - new parent page's id
|
||||
* @param {string} targetPageId - page's id which is changing the parent page
|
||||
*/
|
||||
static async move(oldParentId: string, newParentId: string, targetPageId: string): Promise<void> {
|
||||
public static async move(oldParentId: string, newParentId: string, targetPageId: string): Promise<void> {
|
||||
const oldParentOrder = await Model.get(oldParentId);
|
||||
|
||||
oldParentOrder.remove(targetPageId);
|
||||
|
@ -75,7 +75,7 @@ class PagesOrder {
|
|||
* @param {boolean} ignoreSelf - should we ignore current page in list or not
|
||||
* @returns {Page[]}
|
||||
*/
|
||||
static async getOrderedChildren(pages: Page[], currentPageId: string, parentPageId: string, ignoreSelf = false): Promise<Page[]> {
|
||||
public static async getOrderedChildren(pages: Page[], currentPageId: string, parentPageId: string, ignoreSelf = false): Promise<Page[]> {
|
||||
const children = await Model.get(parentPageId);
|
||||
const unordered = pages.filter(page => page._parent === parentPageId).map(page => page._id);
|
||||
|
||||
|
@ -101,7 +101,7 @@ class PagesOrder {
|
|||
* @param {string} parentPageId - parent page's id that contains both two pages
|
||||
* @param {string} putAbovePageId - page's id above which we put the target page
|
||||
*/
|
||||
static async update(unordered: string[], currentPageId: string, parentPageId: string, putAbovePageId: string): Promise<void> {
|
||||
public static async update(unordered: string[], currentPageId: string, parentPageId: string, putAbovePageId: string): Promise<void> {
|
||||
const pageOrder = await Model.get(parentPageId);
|
||||
|
||||
// Create unique array with ordered and unordered pages id
|
||||
|
@ -114,7 +114,7 @@ class PagesOrder {
|
|||
* @param {string} parentId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static async remove(parentId: string): Promise<void> {
|
||||
public static async remove(parentId: string): Promise<void> {
|
||||
const order = await Model.get(parentId);
|
||||
|
||||
if (!order._id) {
|
||||
|
|
|
@ -1,124 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const file_type_1 = __importDefault(require("file-type"));
|
||||
const node_fetch_1 = __importDefault(require("node-fetch"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const file_1 = __importDefault(require("../models/file"));
|
||||
const crypto_1 = __importDefault(require("../utils/crypto"));
|
||||
const objects_1 = __importDefault(require("../utils/objects"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const random16 = crypto_1.default.random16;
|
||||
/**
|
||||
* @class Transport
|
||||
* @classdesc Transport controller
|
||||
*
|
||||
* Allows to save files from client or fetch them by URL
|
||||
*/
|
||||
class Transport {
|
||||
/**
|
||||
* Saves file passed from client
|
||||
*
|
||||
* @param {object} multerData - file data from multer
|
||||
* @param {string} multerData.originalname - original name of the file
|
||||
* @param {string} multerData.filename - name of the uploaded file
|
||||
* @param {string} multerData.path - path to the uploaded file
|
||||
* @param {number} multerData.size - size of the uploaded file
|
||||
* @param {string} multerData.mimetype - MIME type of the uploaded file
|
||||
*
|
||||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
* @returns {Promise<FileData>}
|
||||
*/
|
||||
static save(multerData, map) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const { originalname: name, path, filename, size, mimetype } = multerData;
|
||||
const file = new file_1.default({
|
||||
name,
|
||||
filename,
|
||||
path,
|
||||
size,
|
||||
mimetype,
|
||||
});
|
||||
yield file.save();
|
||||
let response = file.data;
|
||||
if (map) {
|
||||
response = Transport.composeResponse(file, map);
|
||||
}
|
||||
return response;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Fetches file by passed URL
|
||||
*
|
||||
* @param {string} url - URL of the file
|
||||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
* @returns {Promise<FileData>}
|
||||
*/
|
||||
static fetch(url, map) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const fetchedFile = yield node_fetch_1.default(url);
|
||||
const buffer = yield fetchedFile.buffer();
|
||||
const filename = yield random16();
|
||||
const type = yield file_type_1.default.fromBuffer(buffer);
|
||||
const ext = type ? type.ext : path_1.default.extname(url).slice(1);
|
||||
fs_1.default.writeFileSync(`${config_1.default.get('uploads')}/${filename}.${ext}`, buffer);
|
||||
const file = new file_1.default({
|
||||
name: url,
|
||||
filename: `${filename}.${ext}`,
|
||||
path: `${config_1.default.get('uploads')}/${filename}.${ext}`,
|
||||
size: buffer.length,
|
||||
mimetype: type ? type.mime : fetchedFile.headers.get('content-type'),
|
||||
});
|
||||
yield file.save();
|
||||
let response = file.data;
|
||||
if (map) {
|
||||
response = Transport.composeResponse(file, map);
|
||||
}
|
||||
return response;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Map fields of File object to response by provided map object
|
||||
*
|
||||
* @param {File} file
|
||||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
*
|
||||
*/
|
||||
static composeResponse(file, map) {
|
||||
const response = {};
|
||||
const { data } = file;
|
||||
Object.entries(map).forEach(([name, path]) => {
|
||||
const fields = path.split(':');
|
||||
if (fields.length > 1) {
|
||||
let object = {};
|
||||
const result = object;
|
||||
fields.forEach((field, i) => {
|
||||
if (i === fields.length - 1) {
|
||||
object[field] = data[name];
|
||||
return;
|
||||
}
|
||||
object[field] = {};
|
||||
object = object[field];
|
||||
});
|
||||
objects_1.default(response, result);
|
||||
}
|
||||
else {
|
||||
response[fields[0]] = data[name];
|
||||
}
|
||||
});
|
||||
return response;
|
||||
}
|
||||
}
|
||||
exports.default = Transport;
|
|
@ -34,7 +34,7 @@ class Transport {
|
|||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
* @returns {Promise<FileData>}
|
||||
*/
|
||||
static async save(multerData: Dict, map: Dict): Promise<FileData> {
|
||||
public static async save(multerData: Dict, map: Dict): Promise<FileData> {
|
||||
const { originalname: name, path, filename, size, mimetype } = multerData;
|
||||
|
||||
const file = new Model({
|
||||
|
@ -63,7 +63,7 @@ class Transport {
|
|||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
* @returns {Promise<FileData>}
|
||||
*/
|
||||
static async fetch(url: string, map: Dict): Promise<FileData> {
|
||||
public static async fetch(url: string, map: Dict): Promise<FileData> {
|
||||
const fetchedFile = await fetch(url);
|
||||
const buffer = await fetchedFile.buffer();
|
||||
const filename = await random16();
|
||||
|
@ -99,7 +99,7 @@ class Transport {
|
|||
* @param {object} map - object that represents how should fields of File object should be mapped to response
|
||||
*
|
||||
*/
|
||||
static composeResponse(file: Model, map: Dict): Dict {
|
||||
public static composeResponse(file: Model, map: Dict): Dict {
|
||||
const response: Dict = {};
|
||||
const { data } = file;
|
||||
|
||||
|
|
|
@ -1,33 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const user_1 = __importDefault(require("../models/user"));
|
||||
/**
|
||||
* @class Users
|
||||
* @classdesc Users controller
|
||||
*/
|
||||
class Users {
|
||||
/**
|
||||
* Find and return user model.
|
||||
*
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
static get() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const userDoc = yield user_1.default.get();
|
||||
return userDoc;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = Users;
|
|
@ -11,7 +11,7 @@ class Users {
|
|||
*
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
static async get(): Promise<User|Error> {
|
||||
public static async get(): Promise<User|Error> {
|
||||
const userDoc = await Model.get();
|
||||
|
||||
return userDoc;
|
||||
|
|
|
@ -1,17 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class HttpException extends Error {
|
||||
/**
|
||||
* @param status
|
||||
* @param message
|
||||
*/
|
||||
constructor(status, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
exports.default = HttpException;
|
|
@ -2,8 +2,8 @@
|
|||
*
|
||||
*/
|
||||
class HttpException extends Error {
|
||||
status: number;
|
||||
message: string;
|
||||
public status: number;
|
||||
public message: string;
|
||||
/**
|
||||
* @param status
|
||||
* @param message
|
||||
|
|
|
@ -1,147 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const crypto_1 = __importDefault(require("../utils/crypto"));
|
||||
const index_1 = __importDefault(require("../utils/database/index"));
|
||||
const binaryMD5 = crypto_1.default.binaryMD5;
|
||||
const aliasesDb = index_1.default['aliases'];
|
||||
/**
|
||||
* @class Alias
|
||||
* @classdesc Alias model
|
||||
*
|
||||
* @property {string} _id - alias id
|
||||
* @property {string} hash - alias binary hash
|
||||
* @property {string} type - entity type
|
||||
* @property {boolean} deprecated - indicate if alias deprecated
|
||||
* @property {string} id - entity title
|
||||
*/
|
||||
class Alias {
|
||||
/**
|
||||
* @class
|
||||
*
|
||||
* @param {AliasData} data
|
||||
* @param {string} aliasName - alias of entity
|
||||
*/
|
||||
constructor(data = {}, aliasName = '') {
|
||||
if (data === null) {
|
||||
data = {};
|
||||
}
|
||||
if (data._id) {
|
||||
this._id = data._id;
|
||||
}
|
||||
if (aliasName) {
|
||||
this.hash = binaryMD5(aliasName);
|
||||
}
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Return Alias types
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
static get types() {
|
||||
return {
|
||||
PAGE: 'page',
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Find and return alias with given alias
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static get(aliasName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const hash = binaryMD5(aliasName);
|
||||
let data = yield aliasesDb.findOne({
|
||||
hash: hash,
|
||||
deprecated: false,
|
||||
});
|
||||
if (!data) {
|
||||
data = yield aliasesDb.findOne({ hash: hash });
|
||||
}
|
||||
if (data instanceof Error) {
|
||||
return new Alias();
|
||||
}
|
||||
return new Alias(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Save or update alias data in the database
|
||||
*
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
save() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!this._id) {
|
||||
const insertedRow = yield aliasesDb.insert(this.data);
|
||||
this._id = insertedRow._id;
|
||||
}
|
||||
else {
|
||||
yield aliasesDb.update({ _id: this._id }, this.data);
|
||||
}
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Set AliasData object fields to internal model fields
|
||||
*
|
||||
* @param {AliasData} aliasData
|
||||
*/
|
||||
set data(aliasData) {
|
||||
const { id, type, hash, deprecated } = aliasData;
|
||||
this.id = id || this.id;
|
||||
this.type = type || this.type;
|
||||
this.hash = hash || this.hash;
|
||||
this.deprecated = deprecated || false;
|
||||
}
|
||||
/**
|
||||
* Return AliasData object
|
||||
*
|
||||
* @returns {AliasData}
|
||||
*/
|
||||
get data() {
|
||||
return {
|
||||
_id: this._id,
|
||||
id: this.id,
|
||||
type: this.type,
|
||||
hash: this.hash,
|
||||
deprecated: this.deprecated,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Mark alias as deprecated
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static markAsDeprecated(aliasName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const alias = yield Alias.get(aliasName);
|
||||
alias.deprecated = true;
|
||||
return alias.save();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
destroy() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield aliasesDb.remove({ _id: this._id });
|
||||
delete this._id;
|
||||
return this;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = Alias;
|
|
@ -32,45 +32,11 @@ interface AliasData {
|
|||
* @property {string} id - entity title
|
||||
*/
|
||||
class Alias {
|
||||
_id: string | undefined;
|
||||
hash: string | undefined;
|
||||
type: string | undefined;
|
||||
deprecated: boolean | undefined;
|
||||
id: string | undefined;
|
||||
/**
|
||||
* Return Alias types
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
static get types(): { PAGE: string } {
|
||||
return {
|
||||
PAGE: 'page',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return alias with given alias
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static async get(aliasName: string): Promise<Alias> {
|
||||
const hash = binaryMD5(aliasName);
|
||||
let data = await aliasesDb.findOne({
|
||||
hash: hash,
|
||||
deprecated: false,
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
data = await aliasesDb.findOne({ hash: hash });
|
||||
}
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Alias();
|
||||
}
|
||||
|
||||
return new Alias(data);
|
||||
}
|
||||
public _id: string | undefined;
|
||||
public hash: string | undefined;
|
||||
public type: string | undefined;
|
||||
public deprecated: boolean | undefined;
|
||||
public id: string | undefined;
|
||||
|
||||
/**
|
||||
* @class
|
||||
|
@ -90,13 +56,61 @@ class Alias {
|
|||
}
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Return Alias types
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
public static get types(): { PAGE: string } {
|
||||
return {
|
||||
PAGE: 'page',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return alias with given alias
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
public static async get(aliasName: string): Promise<Alias> {
|
||||
const hash = binaryMD5(aliasName);
|
||||
let data = await aliasesDb.findOne({
|
||||
hash: hash,
|
||||
deprecated: false,
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
data = await aliasesDb.findOne({ hash: hash });
|
||||
}
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Alias();
|
||||
}
|
||||
|
||||
return new Alias(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark alias as deprecated
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
public static async markAsDeprecated(aliasName: string): Promise<Alias> {
|
||||
const alias = await Alias.get(aliasName);
|
||||
|
||||
alias.deprecated = true;
|
||||
|
||||
return alias.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save or update alias data in the database
|
||||
*
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
async save(): Promise<Alias> {
|
||||
public async save(): Promise<Alias> {
|
||||
if (!this._id) {
|
||||
const insertedRow = await aliasesDb.insert(this.data) as { _id: string };
|
||||
|
||||
|
@ -113,7 +127,7 @@ class Alias {
|
|||
*
|
||||
* @param {AliasData} aliasData
|
||||
*/
|
||||
set data(aliasData: AliasData) {
|
||||
public set data(aliasData: AliasData) {
|
||||
const { id, type, hash, deprecated } = aliasData;
|
||||
|
||||
this.id = id || this.id;
|
||||
|
@ -127,7 +141,7 @@ class Alias {
|
|||
*
|
||||
* @returns {AliasData}
|
||||
*/
|
||||
get data(): AliasData {
|
||||
public get data(): AliasData {
|
||||
return {
|
||||
_id: this._id,
|
||||
id: this.id,
|
||||
|
@ -138,23 +152,9 @@ class Alias {
|
|||
}
|
||||
|
||||
/**
|
||||
* Mark alias as deprecated
|
||||
*
|
||||
* @param {string} aliasName - alias of entity
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
static async markAsDeprecated(aliasName: string): Promise<Alias> {
|
||||
const alias = await Alias.get(aliasName);
|
||||
|
||||
alias.deprecated = true;
|
||||
|
||||
return alias.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<Alias>}
|
||||
*/
|
||||
async destroy(): Promise<Alias> {
|
||||
public async destroy(): Promise<Alias> {
|
||||
await aliasesDb.remove({ _id: this._id });
|
||||
|
||||
delete this._id;
|
||||
|
|
|
@ -1,157 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const index_1 = __importDefault(require("../utils/database/index"));
|
||||
const filesDb = index_1.default['files'];
|
||||
/**
|
||||
* @class File
|
||||
* @class File model
|
||||
*
|
||||
* @property {string} _id - file id
|
||||
* @property {string} name - original file name
|
||||
* @property {string} filename - name of uploaded file
|
||||
* @property {string} path - path to uploaded file
|
||||
* @property {string} mimetype - file MIME type
|
||||
* @property {number} size - size of the file in
|
||||
*/
|
||||
class File {
|
||||
/**
|
||||
* @class
|
||||
*
|
||||
* @param {FileData} data
|
||||
*/
|
||||
constructor(data = {}) {
|
||||
if (data === null) {
|
||||
data = {};
|
||||
}
|
||||
if (data._id) {
|
||||
this._id = data._id;
|
||||
}
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} _id - file id
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
static get(_id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield filesDb.findOne({ _id });
|
||||
return new File(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} filename - uploaded filename
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
static getByFilename(filename) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield filesDb.findOne({ filename });
|
||||
return new File(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find all files which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<File[]>}
|
||||
*/
|
||||
static getAll(query = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const docs = yield filesDb.find(query);
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
return Promise.all(docs.map(doc => new File(doc)));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Set FileData object fields to internal model fields
|
||||
*
|
||||
* @param {FileData} fileData
|
||||
*/
|
||||
set data(fileData) {
|
||||
const { name, filename, path, mimetype, size } = fileData;
|
||||
this.name = name || this.name;
|
||||
this.filename = filename || this.filename;
|
||||
this.path = path ? this.processPath(path) : this.path;
|
||||
this.mimetype = mimetype || this.mimetype;
|
||||
this.size = size || this.size;
|
||||
}
|
||||
/**
|
||||
* Return FileData object
|
||||
*
|
||||
* @returns {FileData}
|
||||
*/
|
||||
get data() {
|
||||
return {
|
||||
_id: this._id,
|
||||
name: this.name,
|
||||
filename: this.filename,
|
||||
path: this.path,
|
||||
mimetype: this.mimetype,
|
||||
size: this.size,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Save or update file data in the database
|
||||
*
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
save() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!this._id) {
|
||||
const insertedRow = yield filesDb.insert(this.data);
|
||||
this._id = insertedRow._id;
|
||||
}
|
||||
else {
|
||||
yield filesDb.update({ _id: this._id }, this.data);
|
||||
}
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Remove file data from the database
|
||||
*
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
destroy() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield filesDb.remove({ _id: this._id });
|
||||
delete this._id;
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Removes unnecessary public folder prefix
|
||||
*
|
||||
* @param {string} path
|
||||
* @returns {string}
|
||||
*/
|
||||
processPath(path) {
|
||||
return path.replace(/^public/, '');
|
||||
}
|
||||
/**
|
||||
* Return readable file data
|
||||
*
|
||||
* @returns {FileData}
|
||||
*/
|
||||
toJSON() {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
exports.default = File;
|
|
@ -35,51 +35,12 @@ export interface FileData {
|
|||
* @property {number} size - size of the file in
|
||||
*/
|
||||
class File {
|
||||
_id: string | undefined;
|
||||
name: string | undefined;
|
||||
filename: string | undefined;
|
||||
path: string | undefined;
|
||||
mimetype: string | undefined;
|
||||
size: number | undefined;
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} _id - file id
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
static async get(_id: string): Promise<File> {
|
||||
const data = await filesDb.findOne({ _id });
|
||||
|
||||
return new File(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} filename - uploaded filename
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
static async getByFilename(filename: string): Promise<File> {
|
||||
const data = await filesDb.findOne({ filename });
|
||||
|
||||
return new File(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all files which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<File[]>}
|
||||
*/
|
||||
static async getAll(query: object = {}): Promise<File[]> {
|
||||
const docs = await filesDb.find(query);
|
||||
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new File(doc)));
|
||||
}
|
||||
public _id: string | undefined;
|
||||
public name: string | undefined;
|
||||
public filename: string | undefined;
|
||||
public path: string | undefined;
|
||||
public mimetype: string | undefined;
|
||||
public size: number | undefined;
|
||||
|
||||
/**
|
||||
* @class
|
||||
|
@ -97,13 +58,52 @@ class File {
|
|||
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} _id - file id
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
public static async get(_id: string): Promise<File> {
|
||||
const data = await filesDb.findOne({ _id });
|
||||
|
||||
return new File(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of file with given id
|
||||
*
|
||||
* @param {string} filename - uploaded filename
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
public static async getByFilename(filename: string): Promise<File> {
|
||||
const data = await filesDb.findOne({ filename });
|
||||
|
||||
return new File(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all files which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<File[]>}
|
||||
*/
|
||||
public static async getAll(query: object = {}): Promise<File[]> {
|
||||
const docs = await filesDb.find(query);
|
||||
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new File(doc)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set FileData object fields to internal model fields
|
||||
*
|
||||
* @param {FileData} fileData
|
||||
*/
|
||||
set data(fileData: FileData) {
|
||||
public set data(fileData: FileData) {
|
||||
const { name, filename, path, mimetype, size } = fileData;
|
||||
|
||||
this.name = name || this.name;
|
||||
|
@ -118,7 +118,7 @@ class File {
|
|||
*
|
||||
* @returns {FileData}
|
||||
*/
|
||||
get data(): FileData {
|
||||
public get data(): FileData {
|
||||
return {
|
||||
_id: this._id,
|
||||
name: this.name,
|
||||
|
@ -134,7 +134,7 @@ class File {
|
|||
*
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
async save(): Promise<File> {
|
||||
public async save(): Promise<File> {
|
||||
if (!this._id) {
|
||||
const insertedRow = await filesDb.insert(this.data) as { _id: string };
|
||||
|
||||
|
@ -151,7 +151,7 @@ class File {
|
|||
*
|
||||
* @returns {Promise<File>}
|
||||
*/
|
||||
async destroy(): Promise<File> {
|
||||
public async destroy(): Promise<File> {
|
||||
await filesDb.remove({ _id: this._id });
|
||||
|
||||
delete this._id;
|
||||
|
@ -159,24 +159,24 @@ class File {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return readable file data
|
||||
*
|
||||
* @returns {FileData}
|
||||
*/
|
||||
public toJSON(): FileData {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes unnecessary public folder prefix
|
||||
*
|
||||
* @param {string} path
|
||||
* @returns {string}
|
||||
*/
|
||||
processPath(path: string): string {
|
||||
private processPath(path: string): string {
|
||||
return path.replace(/^public/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return readable file data
|
||||
*
|
||||
* @returns {FileData}
|
||||
*/
|
||||
toJSON(): FileData {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
|
||||
export default File;
|
||||
|
|
|
@ -1,228 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const urlify_1 = __importDefault(require("../utils/urlify"));
|
||||
const index_1 = __importDefault(require("../utils/database/index"));
|
||||
const pagesDb = index_1.default['pages'];
|
||||
/**
|
||||
* @class Page
|
||||
* @class Page model
|
||||
*
|
||||
* @property {string} _id - page id
|
||||
* @property {string} title - page title
|
||||
* @property {string} uri - page uri
|
||||
* @property {*} body - page body
|
||||
* @property {string} _parent - id of parent page
|
||||
*/
|
||||
class Page {
|
||||
/**
|
||||
* @class
|
||||
*
|
||||
* @param {PageData} data
|
||||
*/
|
||||
constructor(data = {}) {
|
||||
if (data === null) {
|
||||
data = {};
|
||||
}
|
||||
if (data._id) {
|
||||
this._id = data._id;
|
||||
}
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Find and return model of page with given id
|
||||
*
|
||||
* @param {string} _id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static get(_id) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield pagesDb.findOne({ _id });
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
return new Page(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find and return model of page with given uri
|
||||
*
|
||||
* @param {string} uri - page uri
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static getByUri(uri) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield pagesDb.findOne({ uri });
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
return new Page(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static getAll(query = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const docs = yield pagesDb.find(query);
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
return Promise.all(docs.map(doc => new Page(doc)));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Set PageData object fields to internal model fields
|
||||
*
|
||||
* @param {PageData} pageData
|
||||
*/
|
||||
set data(pageData) {
|
||||
const { body, parent, uri } = pageData;
|
||||
this.body = body || this.body;
|
||||
this.title = this.extractTitleFromBody();
|
||||
this.uri = uri || '';
|
||||
this._parent = parent || this._parent || '0';
|
||||
}
|
||||
/**
|
||||
* Return PageData object
|
||||
*
|
||||
* @returns {PageData}
|
||||
*/
|
||||
get data() {
|
||||
return {
|
||||
_id: this._id,
|
||||
title: this.title,
|
||||
uri: this.uri,
|
||||
body: this.body,
|
||||
parent: this._parent,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Extract first header from editor data
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
extractTitleFromBody() {
|
||||
const headerBlock = this.body ? this.body.blocks.find((block) => block.type === 'header') : '';
|
||||
return headerBlock ? headerBlock.data.text : '';
|
||||
}
|
||||
/**
|
||||
* Transform title for uri
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
transformTitleToUri() {
|
||||
return urlify_1.default(this.title);
|
||||
}
|
||||
/**
|
||||
* Link given page as parent
|
||||
*
|
||||
* @param {Page} parentPage
|
||||
*/
|
||||
set parent(parentPage) {
|
||||
this._parent = parentPage._id;
|
||||
}
|
||||
/**
|
||||
* Return parent page model
|
||||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
getParent() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield pagesDb.findOne({ _id: this._parent });
|
||||
if (data instanceof Error) {
|
||||
return null;
|
||||
}
|
||||
return new Page(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return child pages models
|
||||
*
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
get children() {
|
||||
return pagesDb.find({ parent: this._id })
|
||||
.then(data => {
|
||||
if (data instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
return data.map(page => new Page(page));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Save or update page data in the database
|
||||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
save() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
this.uri = yield this.composeUri(this.uri);
|
||||
if (!this._id) {
|
||||
const insertedRow = yield pagesDb.insert(this.data);
|
||||
this._id = insertedRow._id;
|
||||
}
|
||||
else {
|
||||
yield pagesDb.update({ _id: this._id }, this.data);
|
||||
}
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Remove page data from the database
|
||||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
destroy() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield pagesDb.remove({ _id: this._id });
|
||||
delete this._id;
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find and return available uri
|
||||
*
|
||||
* @returns {Promise<string>}
|
||||
* @param uri
|
||||
*/
|
||||
composeUri(uri) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let pageWithSameUriCount = 0;
|
||||
if (!this._id) {
|
||||
uri = this.transformTitleToUri();
|
||||
}
|
||||
if (uri) {
|
||||
let pageWithSameUri = yield Page.getByUri(uri);
|
||||
while (pageWithSameUri._id && pageWithSameUri._id !== this._id) {
|
||||
pageWithSameUriCount++;
|
||||
pageWithSameUri = yield Page.getByUri(uri + `-${pageWithSameUriCount}`);
|
||||
}
|
||||
}
|
||||
return pageWithSameUriCount ? uri + `-${pageWithSameUriCount}` : uri;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return readable page data
|
||||
*
|
||||
* @returns {PageData}
|
||||
*/
|
||||
toJSON() {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
exports.default = Page;
|
|
@ -31,58 +31,11 @@ export interface PageData {
|
|||
* @property {string} _parent - id of parent page
|
||||
*/
|
||||
class Page {
|
||||
_id?: string;
|
||||
body: any;
|
||||
title: any;
|
||||
uri: any;
|
||||
_parent: any;
|
||||
/**
|
||||
* Find and return model of page with given id
|
||||
*
|
||||
* @param {string} _id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async get(_id: string): Promise<Page> {
|
||||
const data = await pagesDb.findOne({ _id });
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
|
||||
return new Page(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of page with given uri
|
||||
*
|
||||
* @param {string} uri - page uri
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
static async getByUri(uri: string): Promise<Page> {
|
||||
const data = await pagesDb.findOne({ uri });
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
|
||||
return new Page(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
static async getAll(query: object = {}): Promise<Page[]> {
|
||||
const docs = await pagesDb.find(query);
|
||||
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new Page(doc)));
|
||||
}
|
||||
public _id?: string;
|
||||
public body: any;
|
||||
public title: any;
|
||||
public uri: any;
|
||||
public _parent: any;
|
||||
|
||||
/**
|
||||
* @class
|
||||
|
@ -101,12 +54,60 @@ class Page {
|
|||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of page with given id
|
||||
*
|
||||
* @param {string} _id - page id
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
public static async get(_id: string): Promise<Page> {
|
||||
const data = await pagesDb.findOne({ _id });
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
|
||||
return new Page(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of page with given uri
|
||||
*
|
||||
* @param {string} uri - page uri
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
public static async getByUri(uri: string): Promise<Page> {
|
||||
const data = await pagesDb.findOne({ uri });
|
||||
|
||||
if (data instanceof Error) {
|
||||
return new Page();
|
||||
}
|
||||
|
||||
return new Page(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
public static async getAll(query: object = {}): Promise<Page[]> {
|
||||
const docs = await pagesDb.find(query);
|
||||
|
||||
if (docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new Page(doc)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set PageData object fields to internal model fields
|
||||
*
|
||||
* @param {PageData} pageData
|
||||
*/
|
||||
set data(pageData: PageData) {
|
||||
public set data(pageData: PageData) {
|
||||
const { body, parent, uri } = pageData;
|
||||
|
||||
this.body = body || this.body;
|
||||
|
@ -120,7 +121,7 @@ class Page {
|
|||
*
|
||||
* @returns {PageData}
|
||||
*/
|
||||
get data(): PageData {
|
||||
public get data(): PageData {
|
||||
return {
|
||||
_id: this._id,
|
||||
title: this.title,
|
||||
|
@ -130,32 +131,12 @@ class Page {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract first header from editor data
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
extractTitleFromBody(): string {
|
||||
const headerBlock = this.body ? this.body.blocks.find((block: any) => block.type === 'header') : '';
|
||||
|
||||
return headerBlock ? headerBlock.data.text : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform title for uri
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
transformTitleToUri(): string {
|
||||
return urlify(this.title);
|
||||
}
|
||||
|
||||
/**
|
||||
* Link given page as parent
|
||||
*
|
||||
* @param {Page} parentPage
|
||||
*/
|
||||
set parent(parentPage: Page) {
|
||||
public set parent(parentPage: Page) {
|
||||
this._parent = parentPage._id;
|
||||
}
|
||||
|
||||
|
@ -164,8 +145,7 @@ class Page {
|
|||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
|
||||
async getParent(): Promise<Page|null> {
|
||||
public async getParent(): Promise<Page|null> {
|
||||
const data = await pagesDb.findOne({ _id: this._parent });
|
||||
|
||||
if (data instanceof Error) {
|
||||
|
@ -180,7 +160,7 @@ class Page {
|
|||
*
|
||||
* @returns {Promise<Page[]>}
|
||||
*/
|
||||
get children(): Promise<Page[]> {
|
||||
public get children(): Promise<Page[]> {
|
||||
return pagesDb.find({ parent: this._id })
|
||||
.then(data => {
|
||||
if (data instanceof Error) {
|
||||
|
@ -196,7 +176,7 @@ class Page {
|
|||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
async save(): Promise<Page> {
|
||||
public async save(): Promise<Page> {
|
||||
this.uri = await this.composeUri(this.uri);
|
||||
|
||||
if (!this._id) {
|
||||
|
@ -215,7 +195,7 @@ class Page {
|
|||
*
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
async destroy(): Promise<Page> {
|
||||
public async destroy(): Promise<Page> {
|
||||
await pagesDb.remove({ _id: this._id });
|
||||
|
||||
delete this._id;
|
||||
|
@ -223,13 +203,22 @@ class Page {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return readable page data
|
||||
*
|
||||
* @returns {PageData}
|
||||
*/
|
||||
public toJSON(): PageData {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return available uri
|
||||
*
|
||||
* @returns {Promise<string>}
|
||||
* @param uri
|
||||
*/
|
||||
async composeUri(uri: string): Promise<string> {
|
||||
private async composeUri(uri: string): Promise<string> {
|
||||
let pageWithSameUriCount = 0;
|
||||
|
||||
if (!this._id) {
|
||||
|
@ -249,12 +238,23 @@ class Page {
|
|||
}
|
||||
|
||||
/**
|
||||
* Return readable page data
|
||||
* Extract first header from editor data
|
||||
*
|
||||
* @returns {PageData}
|
||||
* @returns {string}
|
||||
*/
|
||||
toJSON(): PageData {
|
||||
return this.data;
|
||||
private extractTitleFromBody(): string {
|
||||
const headerBlock = this.body ? this.body.blocks.find((block: any) => block.type === 'header') : '';
|
||||
|
||||
return headerBlock ? headerBlock.data.text : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform title for uri
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
private transformTitleToUri(): string {
|
||||
return urlify(this.title);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,222 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const index_1 = __importDefault(require("../utils/database/index"));
|
||||
const db = index_1.default['pagesOrder'];
|
||||
/**
|
||||
* @class PageOrder
|
||||
* @classdesc PageOrder
|
||||
*
|
||||
* Creates order for Pages with children
|
||||
*/
|
||||
class PageOrder {
|
||||
/**
|
||||
* @class
|
||||
*
|
||||
* @param {PageOrderData} data
|
||||
*/
|
||||
constructor(data = {}) {
|
||||
if (data === null) {
|
||||
data = {};
|
||||
}
|
||||
if (data._id) {
|
||||
this._id = data._id;
|
||||
}
|
||||
this.data = data;
|
||||
}
|
||||
/**
|
||||
* Returns current Page's children order
|
||||
*
|
||||
* @param {string} pageId - page's id
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
static get(pageId) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const order = yield db.findOne({ page: pageId });
|
||||
let data = {};
|
||||
if (order instanceof Error || order === null) {
|
||||
data.page = pageId;
|
||||
}
|
||||
else {
|
||||
data = order;
|
||||
}
|
||||
return new PageOrder(data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<PageOrder[]>}
|
||||
*/
|
||||
static getAll(query = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const docs = yield db.find(query);
|
||||
if (docs === null || docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
return Promise.all(docs.map(doc => new PageOrder(doc)));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* constructor data setter
|
||||
*
|
||||
* @param {PageOrderData} pageOrderData
|
||||
*/
|
||||
set data(pageOrderData) {
|
||||
this.page = pageOrderData.page || '0';
|
||||
this.order = pageOrderData.order || [];
|
||||
}
|
||||
/**
|
||||
* Return Page Children order
|
||||
*
|
||||
* @returns {PageOrderData}
|
||||
*/
|
||||
get data() {
|
||||
return {
|
||||
_id: this._id,
|
||||
page: '' + this.page,
|
||||
order: this.order,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Pushes page id to the orders array
|
||||
*
|
||||
* @param {string} pageId - page's id
|
||||
*/
|
||||
push(pageId) {
|
||||
if (typeof pageId === 'string') {
|
||||
if (this.order === undefined) {
|
||||
this.order = [];
|
||||
}
|
||||
this.order.push(pageId);
|
||||
}
|
||||
else {
|
||||
throw new Error('given id is not string');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Removes page id from orders array
|
||||
*
|
||||
* @param {string} pageId - page's id
|
||||
*/
|
||||
remove(pageId) {
|
||||
if (this.order === undefined) {
|
||||
return;
|
||||
}
|
||||
const found = this.order.indexOf(pageId);
|
||||
if (found >= 0) {
|
||||
this.order.splice(found, 1);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param {string} currentPageId - page's id that changes the order
|
||||
* @param {string} putAbovePageId - page's id above which we put the target page
|
||||
*
|
||||
* @returns void
|
||||
*/
|
||||
putAbove(currentPageId, putAbovePageId) {
|
||||
if (this.order === undefined) {
|
||||
return;
|
||||
}
|
||||
const found1 = this.order.indexOf(putAbovePageId);
|
||||
const found2 = this.order.indexOf(currentPageId);
|
||||
if (found1 === -1 || found2 === -1) {
|
||||
return;
|
||||
}
|
||||
const margin = found1 < found2 ? 1 : 0;
|
||||
this.order.splice(found1, 0, currentPageId);
|
||||
this.order.splice(found2 + margin, 1);
|
||||
}
|
||||
/**
|
||||
* Returns page before passed page with id
|
||||
*
|
||||
* @param {string} pageId
|
||||
*/
|
||||
getPageBefore(pageId) {
|
||||
if (this.order === undefined) {
|
||||
return null;
|
||||
}
|
||||
const currentPageInOrder = this.order.indexOf(pageId);
|
||||
/**
|
||||
* If page not found or first return nothing
|
||||
*/
|
||||
if (currentPageInOrder <= 0) {
|
||||
return null;
|
||||
}
|
||||
return this.order[currentPageInOrder - 1];
|
||||
}
|
||||
/**
|
||||
* Returns page before passed page with id
|
||||
*
|
||||
* @param pageId
|
||||
*/
|
||||
getPageAfter(pageId) {
|
||||
if (this.order === undefined) {
|
||||
return null;
|
||||
}
|
||||
const currentPageInOrder = this.order.indexOf(pageId);
|
||||
/**
|
||||
* If page not found or is last
|
||||
*/
|
||||
if (currentPageInOrder === -1 || currentPageInOrder === this.order.length - 1) {
|
||||
return null;
|
||||
}
|
||||
return this.order[currentPageInOrder + 1];
|
||||
}
|
||||
/**
|
||||
* @param {string[]} order - define new order
|
||||
*/
|
||||
set order(order) {
|
||||
this._order = order;
|
||||
}
|
||||
/**
|
||||
* Returns ordered list
|
||||
*
|
||||
* @returns {string[]}
|
||||
*/
|
||||
get order() {
|
||||
return this._order || [];
|
||||
}
|
||||
/**
|
||||
* Save or update page data in the database
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
save() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!this._id) {
|
||||
const insertedRow = yield db.insert(this.data);
|
||||
if (!(insertedRow instanceof Error)) {
|
||||
this._id = insertedRow._id;
|
||||
}
|
||||
}
|
||||
else {
|
||||
yield db.update({ _id: this._id }, this.data);
|
||||
}
|
||||
return this;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Remove page data from the database
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
destroy() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield db.remove({ _id: this._id });
|
||||
delete this._id;
|
||||
// return this;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = PageOrder;
|
|
@ -22,44 +22,10 @@ export interface PageOrderData {
|
|||
* Creates order for Pages with children
|
||||
*/
|
||||
class PageOrder {
|
||||
_id?: string;
|
||||
page?: string;
|
||||
_order?: string[];
|
||||
/**
|
||||
* Returns current Page's children order
|
||||
*
|
||||
* @param {string} pageId - page's id
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
static async get(pageId: string): Promise<PageOrder> {
|
||||
const order = await db.findOne({ page: pageId });
|
||||
public _id?: string;
|
||||
public page?: string;
|
||||
private _order?: string[];
|
||||
|
||||
let data = {} as PageOrderData;
|
||||
|
||||
if (order instanceof Error || order === null) {
|
||||
data.page = pageId;
|
||||
} else {
|
||||
data = order;
|
||||
}
|
||||
|
||||
return new PageOrder(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<PageOrder[]>}
|
||||
*/
|
||||
static async getAll(query: object = {}): Promise<PageOrder[]> {
|
||||
const docs = await db.find(query);
|
||||
|
||||
if (docs === null || docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new PageOrder(doc)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @class
|
||||
|
@ -78,12 +44,48 @@ class PageOrder {
|
|||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current Page's children order
|
||||
*
|
||||
* @param {string} pageId - page's id
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
public static async get(pageId: string): Promise<PageOrder> {
|
||||
const order = await db.findOne({ page: pageId });
|
||||
|
||||
let data = {} as PageOrderData;
|
||||
|
||||
if (order instanceof Error || order === null) {
|
||||
data.page = pageId;
|
||||
} else {
|
||||
data = order;
|
||||
}
|
||||
|
||||
return new PageOrder(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all pages which match passed query object
|
||||
*
|
||||
* @param {object} query
|
||||
* @returns {Promise<PageOrder[]>}
|
||||
*/
|
||||
public static async getAll(query: object = {}): Promise<PageOrder[]> {
|
||||
const docs = await db.find(query);
|
||||
|
||||
if (docs === null || docs instanceof Error) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Promise.all(docs.map(doc => new PageOrder(doc)));
|
||||
}
|
||||
|
||||
/**
|
||||
* constructor data setter
|
||||
*
|
||||
* @param {PageOrderData} pageOrderData
|
||||
*/
|
||||
set data(pageOrderData: PageOrderData) {
|
||||
public set data(pageOrderData: PageOrderData) {
|
||||
this.page = pageOrderData.page || '0';
|
||||
this.order = pageOrderData.order || [];
|
||||
}
|
||||
|
@ -93,7 +95,7 @@ class PageOrder {
|
|||
*
|
||||
* @returns {PageOrderData}
|
||||
*/
|
||||
get data(): PageOrderData {
|
||||
public get data(): PageOrderData {
|
||||
return {
|
||||
_id: this._id,
|
||||
page: '' + this.page,
|
||||
|
@ -106,7 +108,7 @@ class PageOrder {
|
|||
*
|
||||
* @param {string} pageId - page's id
|
||||
*/
|
||||
push(pageId: string): void {
|
||||
public push(pageId: string): void {
|
||||
if (typeof pageId === 'string') {
|
||||
if (this.order === undefined) {
|
||||
this.order = [];
|
||||
|
@ -122,7 +124,7 @@ class PageOrder {
|
|||
*
|
||||
* @param {string} pageId - page's id
|
||||
*/
|
||||
remove(pageId: string): void {
|
||||
public remove(pageId: string): void {
|
||||
if (this.order === undefined) {
|
||||
return;
|
||||
}
|
||||
|
@ -138,9 +140,9 @@ class PageOrder {
|
|||
* @param {string} currentPageId - page's id that changes the order
|
||||
* @param {string} putAbovePageId - page's id above which we put the target page
|
||||
*
|
||||
* @returns void
|
||||
* @returns {void}
|
||||
*/
|
||||
putAbove(currentPageId: string, putAbovePageId: string): void {
|
||||
public putAbove(currentPageId: string, putAbovePageId: string): void {
|
||||
if (this.order === undefined) {
|
||||
return;
|
||||
}
|
||||
|
@ -163,7 +165,7 @@ class PageOrder {
|
|||
*
|
||||
* @param {string} pageId
|
||||
*/
|
||||
getPageBefore(pageId: string): string | null {
|
||||
public getPageBefore(pageId: string): string | null {
|
||||
if (this.order === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
@ -185,7 +187,7 @@ class PageOrder {
|
|||
*
|
||||
* @param pageId
|
||||
*/
|
||||
getPageAfter(pageId: string): string | null {
|
||||
public getPageAfter(pageId: string): string | null {
|
||||
if (this.order === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
@ -205,7 +207,7 @@ class PageOrder {
|
|||
/**
|
||||
* @param {string[]} order - define new order
|
||||
*/
|
||||
set order(order: string[]) {
|
||||
public set order(order: string[]) {
|
||||
this._order = order;
|
||||
}
|
||||
|
||||
|
@ -214,15 +216,16 @@ class PageOrder {
|
|||
*
|
||||
* @returns {string[]}
|
||||
*/
|
||||
get order(): string[] {
|
||||
public get order(): string[] {
|
||||
return this._order || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Save or update page data in the database
|
||||
*
|
||||
* @returns {Promise<PageOrder>}
|
||||
*/
|
||||
async save(): Promise<PageOrder> {
|
||||
public async save(): Promise<PageOrder> {
|
||||
if (!this._id) {
|
||||
const insertedRow = await db.insert(this.data) as { _id: string};
|
||||
|
||||
|
@ -238,9 +241,10 @@ class PageOrder {
|
|||
|
||||
/**
|
||||
* Remove page data from the database
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async destroy(): Promise<void> {
|
||||
public async destroy(): Promise<void> {
|
||||
await db.remove({ _id: this._id });
|
||||
|
||||
delete this._id;
|
||||
|
|
|
@ -1,48 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const index_1 = __importDefault(require("../utils/database/index"));
|
||||
const db = index_1.default['password'];
|
||||
/**
|
||||
* @class User
|
||||
* @class User model
|
||||
*
|
||||
* @property {string} passHash - hashed password
|
||||
*/
|
||||
class User {
|
||||
/**
|
||||
* @class
|
||||
*
|
||||
* @param {UserData} userData
|
||||
*/
|
||||
constructor(userData) {
|
||||
this.passHash = userData.passHash;
|
||||
}
|
||||
/**
|
||||
* Find and return model of user.
|
||||
* User is only one.
|
||||
*
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
static get() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const data = yield db.findOne({});
|
||||
if (data instanceof Error || data === null) {
|
||||
return new Error('User not found');
|
||||
}
|
||||
return new User(data);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.default = User;
|
|
@ -13,22 +13,7 @@ interface UserData {
|
|||
* @property {string} passHash - hashed password
|
||||
*/
|
||||
class User {
|
||||
passHash: string;
|
||||
/**
|
||||
* Find and return model of user.
|
||||
* User is only one.
|
||||
*
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
static async get(): Promise<User|Error> {
|
||||
const data = await db.findOne({});
|
||||
|
||||
if (data instanceof Error || data === null) {
|
||||
return new Error('User not found');
|
||||
}
|
||||
|
||||
return new User(data as UserData);
|
||||
}
|
||||
public passHash: string;
|
||||
|
||||
/**
|
||||
* @class
|
||||
|
@ -38,6 +23,22 @@ class User {
|
|||
constructor(userData: UserData) {
|
||||
this.passHash = userData.passHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return model of user.
|
||||
* User is only one.
|
||||
*
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
public static async get(): Promise<User|Error> {
|
||||
const data = await db.findOne({});
|
||||
|
||||
if (data instanceof Error || data === null) {
|
||||
return new Error('User not found');
|
||||
}
|
||||
|
||||
return new User(data as UserData);
|
||||
}
|
||||
}
|
||||
|
||||
export default User;
|
||||
|
|
|
@ -1,56 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const aliases_1 = __importDefault(require("../controllers/aliases"));
|
||||
const pages_1 = __importDefault(require("../controllers/pages"));
|
||||
const alias_1 = __importDefault(require("../models/alias"));
|
||||
const token_1 = __importDefault(require("./middlewares/token"));
|
||||
const router = express_1.default.Router();
|
||||
/**
|
||||
* GET /*
|
||||
*
|
||||
* Return document with given alias
|
||||
*/
|
||||
router.get('*', token_1.default, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
let url = req.originalUrl.slice(1); // Cuts first '/' character
|
||||
const queryParamsIndex = url.indexOf('?');
|
||||
if (queryParamsIndex !== -1) {
|
||||
url = url.slice(0, queryParamsIndex); // Cuts off query params
|
||||
}
|
||||
const alias = yield aliases_1.default.get(url);
|
||||
if (alias.id === undefined) {
|
||||
throw new Error('Alias not found');
|
||||
}
|
||||
switch (alias.type) {
|
||||
case alias_1.default.types.PAGE: {
|
||||
const page = yield pages_1.default.get(alias.id);
|
||||
const pageParent = page.parent;
|
||||
res.render('pages/page', {
|
||||
page,
|
||||
pageParent,
|
||||
config: req.app.locals.config,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,14 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const router = express_1.default.Router();
|
||||
const pages_1 = __importDefault(require("./pages"));
|
||||
const transport_1 = __importDefault(require("./transport"));
|
||||
const links_1 = __importDefault(require("./links"));
|
||||
router.use('/', pages_1.default);
|
||||
router.use('/', transport_1.default);
|
||||
router.use('/', links_1.default);
|
||||
exports.default = router;
|
|
@ -1,9 +1,9 @@
|
|||
import express from "express";
|
||||
const router = express.Router();
|
||||
import express from 'express';
|
||||
|
||||
import pagesAPI from "./pages";
|
||||
import transportAPI from "./transport";
|
||||
import linksAPI from "./links";
|
||||
import pagesAPI from './pages';
|
||||
import transportAPI from './transport';
|
||||
import linksAPI from './links';
|
||||
const router = express.Router();
|
||||
|
||||
router.use('/', pagesAPI);
|
||||
router.use('/', transportAPI);
|
||||
|
|
|
@ -1,56 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const open_graph_scraper_1 = __importDefault(require("open-graph-scraper"));
|
||||
const router = express_1.default.Router();
|
||||
/**
|
||||
* Accept file url to fetch
|
||||
*/
|
||||
router.get('/fetchUrl', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const response = {
|
||||
success: 0
|
||||
};
|
||||
if (!req.query.url) {
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
if (typeof req.query.url !== 'string') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const linkData = (yield open_graph_scraper_1.default({ url: req.query.url })).result;
|
||||
if (!linkData.success) {
|
||||
return;
|
||||
}
|
||||
response.success = 1;
|
||||
response.meta = {
|
||||
title: linkData.ogTitle,
|
||||
description: linkData.ogDescription,
|
||||
site_name: linkData.ogSiteName,
|
||||
image: {
|
||||
url: undefined
|
||||
}
|
||||
};
|
||||
if (linkData.ogImage !== undefined) {
|
||||
response.meta.image = { url: linkData.ogImage.toString() };
|
||||
}
|
||||
res.status(200).json(response);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
res.status(500).json(response);
|
||||
}
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,5 +1,5 @@
|
|||
import express, { Request, Response } from "express";
|
||||
import ogs from "open-graph-scraper";
|
||||
import express, { Request, Response } from 'express';
|
||||
import ogs from 'open-graph-scraper';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
|
@ -8,7 +8,7 @@ interface ResponseData {
|
|||
meta?: {
|
||||
title: string | undefined;
|
||||
description: string | undefined;
|
||||
site_name: string | undefined;
|
||||
siteName: string | undefined;
|
||||
image: { url: string | undefined }
|
||||
}
|
||||
}
|
||||
|
@ -18,11 +18,12 @@ interface ResponseData {
|
|||
*/
|
||||
router.get('/fetchUrl', async (req: Request, res: Response) => {
|
||||
const response: ResponseData = {
|
||||
success: 0
|
||||
success: 0,
|
||||
};
|
||||
|
||||
if (!req.query.url) {
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -41,14 +42,14 @@ router.get('/fetchUrl', async (req: Request, res: Response) => {
|
|||
response.meta = {
|
||||
title: linkData.ogTitle,
|
||||
description: linkData.ogDescription,
|
||||
site_name: linkData.ogSiteName,
|
||||
siteName: linkData.ogSiteName,
|
||||
image: {
|
||||
url: undefined
|
||||
}
|
||||
url: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
if (linkData.ogImage !== undefined) {
|
||||
response.meta.image = { url: linkData.ogImage.toString()}
|
||||
response.meta.image = { url: linkData.ogImage.toString() };
|
||||
}
|
||||
|
||||
res.status(200).json(response);
|
||||
|
|
|
@ -1,196 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const pages_1 = __importDefault(require("../../controllers/pages"));
|
||||
const pagesOrder_1 = __importDefault(require("../../controllers/pagesOrder"));
|
||||
const multer_1 = __importDefault(require("multer"));
|
||||
const router = express_1.default.Router();
|
||||
const multer = multer_1.default();
|
||||
/**
|
||||
* GET /page/:id
|
||||
*
|
||||
* Return PageData of page with given id
|
||||
*/
|
||||
router.get('/page/:id', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
const page = yield pages_1.default.get(req.params.id);
|
||||
res.json({
|
||||
success: true,
|
||||
result: page.data
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* GET /pages
|
||||
*
|
||||
* Return PageData for all pages
|
||||
*/
|
||||
router.get('/pages', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
const pages = yield pages_1.default.getAll();
|
||||
res.json({
|
||||
success: true,
|
||||
result: pages
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* PUT /page
|
||||
*
|
||||
* Create new page in the database
|
||||
*/
|
||||
router.put('/page', multer.none(), (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
const { title, body, parent } = req.body;
|
||||
const page = yield pages_1.default.insert({ title, body, parent });
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
}
|
||||
/** push to the orders array */
|
||||
yield pagesOrder_1.default.push(parent, page._id);
|
||||
res.json({
|
||||
success: true,
|
||||
result: page
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* POST /page/:id
|
||||
*
|
||||
* Update page data in the database
|
||||
*/
|
||||
router.post('/page/:id', multer.none(), (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const { id } = req.params;
|
||||
try {
|
||||
const { title, body, parent, putAbovePageId, uri } = req.body;
|
||||
const pages = yield pages_1.default.getAll();
|
||||
let page = yield pages_1.default.get(id);
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
}
|
||||
if (page._parent !== parent) {
|
||||
yield pagesOrder_1.default.move(page._parent, parent, id);
|
||||
}
|
||||
else {
|
||||
if (putAbovePageId && putAbovePageId !== '0') {
|
||||
const unordered = pages.filter(_page => _page._parent === page._parent).map(_page => _page._id);
|
||||
const unOrdered = [];
|
||||
unordered.forEach((item, index) => {
|
||||
if (typeof item === 'string') {
|
||||
unOrdered.push(item);
|
||||
}
|
||||
});
|
||||
yield pagesOrder_1.default.update(unOrdered, page._id, page._parent, putAbovePageId);
|
||||
}
|
||||
}
|
||||
page = yield pages_1.default.update(id, { title, body, parent, uri });
|
||||
res.json({
|
||||
success: true,
|
||||
result: page
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* DELETE /page/:id
|
||||
*
|
||||
* Remove page from the database
|
||||
*/
|
||||
router.delete('/page/:id', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
const pageId = req.params.id;
|
||||
const page = yield pages_1.default.get(pageId);
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
}
|
||||
const parentPageOrder = yield pagesOrder_1.default.get(page._parent);
|
||||
const pageBeforeId = parentPageOrder.getPageBefore(page._id);
|
||||
const pageAfterId = parentPageOrder.getPageAfter(page._id);
|
||||
let pageToRedirect;
|
||||
if (pageBeforeId) {
|
||||
pageToRedirect = yield pages_1.default.get(pageBeforeId);
|
||||
}
|
||||
else if (pageAfterId) {
|
||||
pageToRedirect = yield pages_1.default.get(pageAfterId);
|
||||
}
|
||||
else {
|
||||
pageToRedirect = page._parent !== '0' ? yield pages_1.default.get(page._parent) : null;
|
||||
}
|
||||
/**
|
||||
* remove current page and go deeper to remove children with orders
|
||||
*
|
||||
* @param {string} startFrom
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const deleteRecursively = (startFrom) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let order = [];
|
||||
try {
|
||||
const children = yield pagesOrder_1.default.get(startFrom);
|
||||
order = children.order;
|
||||
}
|
||||
catch (e) {
|
||||
order = [];
|
||||
}
|
||||
order.forEach((id) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
yield deleteRecursively(id);
|
||||
}));
|
||||
yield pages_1.default.remove(startFrom);
|
||||
try {
|
||||
yield pagesOrder_1.default.remove(startFrom);
|
||||
}
|
||||
catch (e) {
|
||||
order = [];
|
||||
}
|
||||
});
|
||||
yield deleteRecursively(req.params.id);
|
||||
// remove also from parent's order
|
||||
parentPageOrder.remove(req.params.id);
|
||||
yield parentPageOrder.save();
|
||||
res.json({
|
||||
success: true,
|
||||
result: pageToRedirect
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,7 +1,7 @@
|
|||
import express, { Request, Response } from "express";
|
||||
import Pages from "../../controllers/pages";
|
||||
import PagesOrder from "../../controllers/pagesOrder";
|
||||
import multerFunc from "multer";
|
||||
import express, { Request, Response } from 'express';
|
||||
import Pages from '../../controllers/pages';
|
||||
import PagesOrder from '../../controllers/pagesOrder';
|
||||
import multerFunc from 'multer';
|
||||
|
||||
const router = express.Router();
|
||||
const multer = multerFunc();
|
||||
|
@ -18,12 +18,12 @@ router.get('/page/:id', async (req: Request, res: Response) => {
|
|||
|
||||
res.json({
|
||||
success: true,
|
||||
result: page.data
|
||||
result: page.data,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
@ -39,12 +39,12 @@ router.get('/pages', async (req: Request, res: Response) => {
|
|||
|
||||
res.json({
|
||||
success: true,
|
||||
result: pages
|
||||
result: pages,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
@ -57,10 +57,14 @@ router.get('/pages', async (req: Request, res: Response) => {
|
|||
router.put('/page', multer.none(), async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { title, body, parent } = req.body;
|
||||
const page = await Pages.insert({ title, body, parent });
|
||||
const page = await Pages.insert({
|
||||
title,
|
||||
body,
|
||||
parent,
|
||||
});
|
||||
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
throw new Error('Page not found');
|
||||
}
|
||||
|
||||
/** push to the orders array */
|
||||
|
@ -68,12 +72,12 @@ router.put('/page', multer.none(), async (req: Request, res: Response) => {
|
|||
|
||||
res.json({
|
||||
success: true,
|
||||
result: page
|
||||
result: page,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
@ -92,7 +96,7 @@ router.post('/page/:id', multer.none(), async (req: Request, res: Response) => {
|
|||
let page = await Pages.get(id);
|
||||
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
throw new Error('Page not found');
|
||||
}
|
||||
|
||||
if (page._parent !== parent) {
|
||||
|
@ -107,21 +111,26 @@ router.post('/page/:id', multer.none(), async (req: Request, res: Response) => {
|
|||
if (typeof item === 'string') {
|
||||
unOrdered.push(item);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
await PagesOrder.update(unOrdered, page._id, page._parent, putAbovePageId);
|
||||
}
|
||||
}
|
||||
|
||||
page = await Pages.update(id, { title, body, parent, uri });
|
||||
page = await Pages.update(id, {
|
||||
title,
|
||||
body,
|
||||
parent,
|
||||
uri,
|
||||
});
|
||||
res.json({
|
||||
success: true,
|
||||
result: page
|
||||
result: page,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
@ -137,7 +146,7 @@ router.delete('/page/:id', async (req: Request, res: Response) => {
|
|||
const page = await Pages.get(pageId);
|
||||
|
||||
if (page._id === undefined) {
|
||||
throw new Error("Page not found");
|
||||
throw new Error('Page not found');
|
||||
}
|
||||
|
||||
const parentPageOrder = await PagesOrder.get(page._parent);
|
||||
|
@ -179,7 +188,7 @@ router.delete('/page/:id', async (req: Request, res: Response) => {
|
|||
try {
|
||||
await PagesOrder.remove(startFrom);
|
||||
} catch (e) {
|
||||
order = []
|
||||
order = [];
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -191,12 +200,12 @@ router.delete('/page/:id', async (req: Request, res: Response) => {
|
|||
|
||||
res.json({
|
||||
success: true,
|
||||
result: pageToRedirect
|
||||
result: pageToRedirect,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: err.message
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
|
@ -1,121 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = require("express");
|
||||
const multer_1 = __importDefault(require("multer"));
|
||||
const mime_1 = __importDefault(require("mime"));
|
||||
const mkdirp_1 = __importDefault(require("mkdirp"));
|
||||
const transport_1 = __importDefault(require("../../controllers/transport"));
|
||||
const crypto_1 = require("../../utils/crypto");
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const router = express_1.Router();
|
||||
/**
|
||||
* Multer storage for uploaded files and images
|
||||
* @type {StorageEngine}
|
||||
*/
|
||||
const storage = multer_1.default.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
const dir = config_1.default.get('uploads') || 'public/uploads';
|
||||
mkdirp_1.default(dir);
|
||||
cb(null, dir);
|
||||
},
|
||||
filename: (req, file, cb) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const filename = yield crypto_1.random16();
|
||||
cb(null, `${filename}.${mime_1.default.getExtension(file.mimetype)}`);
|
||||
})
|
||||
});
|
||||
/**
|
||||
* Multer middleware for image uploading
|
||||
*/
|
||||
const imageUploader = multer_1.default({
|
||||
storage: storage,
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (!/image/.test(file.mimetype) && !/video\/mp4/.test(file.mimetype)) {
|
||||
cb(null, false);
|
||||
return;
|
||||
}
|
||||
cb(null, true);
|
||||
}
|
||||
}).fields([{ name: 'image', maxCount: 1 }]);
|
||||
/**
|
||||
* Multer middleware for file uploading
|
||||
*/
|
||||
const fileUploader = multer_1.default({
|
||||
storage: storage
|
||||
}).fields([{ name: 'file', maxCount: 1 }]);
|
||||
/**
|
||||
* Accepts images to upload
|
||||
*/
|
||||
router.post('/transport/image', imageUploader, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const response = { success: 0, message: '' };
|
||||
if (req.files === undefined) {
|
||||
response.message = 'No files found';
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
if (!('image' in req.files)) {
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object.assign(response, yield transport_1.default.save(req.files.image[0], req.body.map ? JSON.parse(req.body.map) : undefined));
|
||||
response.success = 1;
|
||||
res.status(200).json(response);
|
||||
}
|
||||
catch (e) {
|
||||
res.status(500).json(response);
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* Accepts files to upload
|
||||
*/
|
||||
router.post('/transport/file', fileUploader, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const response = { success: 0 };
|
||||
if (req.files === undefined) {
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
if (!('file' in req.files)) {
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object.assign(response, yield transport_1.default.save(req.files.file[0], req.body.map ? JSON.parse(req.body.map) : undefined));
|
||||
response.success = 1;
|
||||
res.status(200).json(response);
|
||||
}
|
||||
catch (e) {
|
||||
res.status(500).json(response);
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* Accept file url to fetch
|
||||
*/
|
||||
router.post('/transport/fetch', multer_1.default().none(), (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const response = { success: 0 };
|
||||
if (!req.body.url) {
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object.assign(response, yield transport_1.default.fetch(req.body.url, req.body.map ? JSON.parse(req.body.map) : undefined));
|
||||
response.success = 1;
|
||||
res.status(200).json(response);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
res.status(500).json(response);
|
||||
}
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,15 +1,16 @@
|
|||
import { Request, Response, Router } from "express";
|
||||
import multer, { StorageEngine } from "multer";
|
||||
import mime from "mime";
|
||||
import mkdirp from "mkdirp";
|
||||
import Transport from "../../controllers/transport";
|
||||
import { random16 } from "../../utils/crypto";
|
||||
import config from "config";
|
||||
import { Request, Response, Router } from 'express';
|
||||
import multer, { StorageEngine } from 'multer';
|
||||
import mime from 'mime';
|
||||
import mkdirp from 'mkdirp';
|
||||
import Transport from '../../controllers/transport';
|
||||
import { random16 } from '../../utils/crypto';
|
||||
import config from 'config';
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* Multer storage for uploaded files and images
|
||||
*
|
||||
* @type {StorageEngine}
|
||||
*/
|
||||
const storage: StorageEngine = multer.diskStorage({
|
||||
|
@ -23,7 +24,7 @@ const storage: StorageEngine = multer.diskStorage({
|
|||
const filename = await random16();
|
||||
|
||||
cb(null, `${filename}.${mime.getExtension(file.mimetype)}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
|
@ -34,33 +35,45 @@ const imageUploader = multer({
|
|||
fileFilter: (req, file, cb) => {
|
||||
if (!/image/.test(file.mimetype) && !/video\/mp4/.test(file.mimetype)) {
|
||||
cb(null, false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
cb(null, true);
|
||||
}
|
||||
}).fields([ { name: 'image', maxCount: 1 } ]);
|
||||
},
|
||||
}).fields([ {
|
||||
name: 'image',
|
||||
maxCount: 1,
|
||||
} ]);
|
||||
|
||||
/**
|
||||
* Multer middleware for file uploading
|
||||
*/
|
||||
const fileUploader = multer({
|
||||
storage: storage
|
||||
}).fields([ { name: 'file', maxCount: 1 } ]);
|
||||
storage: storage,
|
||||
}).fields([ {
|
||||
name: 'file',
|
||||
maxCount: 1,
|
||||
} ]);
|
||||
|
||||
/**
|
||||
* Accepts images to upload
|
||||
*/
|
||||
router.post('/transport/image', imageUploader, async (req: Request, res: Response) => {
|
||||
const response = { success: 0, message: ''};
|
||||
const response = {
|
||||
success: 0,
|
||||
message: '',
|
||||
};
|
||||
|
||||
if (req.files === undefined) {
|
||||
response.message = 'No files found';
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
if (!('image' in req.files)) {
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -85,10 +98,12 @@ router.post('/transport/file', fileUploader, async (req: Request, res: Response)
|
|||
|
||||
if (req.files === undefined) {
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
if (!('file' in req.files)) {
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -113,6 +128,7 @@ router.post('/transport/fetch', multer().none(), async (req: Request, res: Respo
|
|||
|
||||
if (!req.body.url) {
|
||||
res.status(400).json(response);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,88 +0,0 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
||||
const users_1 = __importDefault(require("../controllers/users"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const bcrypt_1 = __importDefault(require("bcrypt"));
|
||||
const csurf_1 = __importDefault(require("csurf"));
|
||||
const dotenv = __importStar(require("dotenv"));
|
||||
dotenv.config();
|
||||
const router = express_1.default.Router();
|
||||
const csrfProtection = csurf_1.default({ cookie: true });
|
||||
const parseForm = express_1.default.urlencoded({ extended: false });
|
||||
/**
|
||||
* Authorization page
|
||||
*/
|
||||
router.get('/auth', csrfProtection, function (req, res) {
|
||||
res.render('auth', {
|
||||
title: 'Login page',
|
||||
csrfToken: req.csrfToken(),
|
||||
});
|
||||
});
|
||||
/**
|
||||
* Process given password
|
||||
*/
|
||||
router.post('/auth', parseForm, csrfProtection, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const userDoc = yield users_1.default.get();
|
||||
if (!userDoc || userDoc instanceof Error) {
|
||||
res.render('auth', {
|
||||
title: 'Login page',
|
||||
header: 'Password not set',
|
||||
csrfToken: req.csrfToken(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const passHash = userDoc.passHash;
|
||||
bcrypt_1.default.compare(req.body.password, passHash, (err, result) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
if (err || result === false) {
|
||||
res.render('auth', {
|
||||
title: 'Login page',
|
||||
header: 'Wrong password',
|
||||
csrfToken: req.csrfToken(),
|
||||
});
|
||||
}
|
||||
const token = jsonwebtoken_1.default.sign({
|
||||
iss: 'Codex Team',
|
||||
sub: 'auth',
|
||||
iat: Date.now(),
|
||||
}, passHash + config_1.default.get('secret'));
|
||||
res.cookie('authToken', token, {
|
||||
httpOnly: true,
|
||||
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year
|
||||
});
|
||||
res.redirect('/');
|
||||
}));
|
||||
}));
|
||||
exports.default = router;
|
|
@ -5,7 +5,7 @@ import config from 'config';
|
|||
import bcrypt from 'bcrypt';
|
||||
import csrf from 'csurf';
|
||||
|
||||
import * as dotenv from "dotenv";
|
||||
import * as dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
const router = express.Router();
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const token_1 = __importDefault(require("./middlewares/token"));
|
||||
const router = express_1.default.Router();
|
||||
/* GET home page. */
|
||||
router.get('/', token_1.default, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const config = req.app.locals.config;
|
||||
if (config.startPage) {
|
||||
return res.redirect(config.startPage);
|
||||
}
|
||||
res.render('pages/index', { isAuthorized: res.locals.isAuthorized });
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,19 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const home_1 = __importDefault(require("./home"));
|
||||
const pages_1 = __importDefault(require("./pages"));
|
||||
const auth_1 = __importDefault(require("./auth"));
|
||||
const aliases_1 = __importDefault(require("./aliases"));
|
||||
const api_1 = __importDefault(require("./api"));
|
||||
const pages_2 = __importDefault(require("./middlewares/pages"));
|
||||
const router = express_1.default.Router();
|
||||
router.use('/', pages_2.default, home_1.default);
|
||||
router.use('/', pages_2.default, pages_1.default);
|
||||
router.use('/', pages_2.default, auth_1.default);
|
||||
router.use('/api', api_1.default);
|
||||
router.use('/', aliases_1.default);
|
||||
exports.default = router;
|
|
@ -1,17 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Middleware for checking locals.isAuthorized property, which allows to edit/create pages
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
function allowEdit(req, res, next) {
|
||||
if (res.locals.isAuthorized) {
|
||||
next();
|
||||
}
|
||||
else {
|
||||
res.redirect('/auth');
|
||||
}
|
||||
}
|
||||
exports.default = allowEdit;
|
|
@ -1,12 +1,13 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Middleware for checking locals.isAuthorized property, which allows to edit/create pages
|
||||
*
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
export default function allowEdit(req: Request, res: Response, next: NextFunction) {
|
||||
export default function allowEdit(req: Request, res: Response, next: NextFunction): void {
|
||||
if (res.locals.isAuthorized) {
|
||||
next();
|
||||
} else {
|
||||
|
|
|
@ -1,80 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const pages_1 = __importDefault(require("../../controllers/pages"));
|
||||
const pagesOrder_1 = __importDefault(require("../../controllers/pagesOrder"));
|
||||
const asyncMiddleware_1 = __importDefault(require("../../utils/asyncMiddleware"));
|
||||
/**
|
||||
* Process one-level pages list to parent-children list
|
||||
*
|
||||
* @param {string} parentPageId - parent page id
|
||||
* @param {Page[]} pages - list of all available pages
|
||||
* @param {PagesOrder[]} pagesOrder - list of pages order
|
||||
* @param {number} level
|
||||
* @param {number} currentLevel
|
||||
*
|
||||
* @return {Page[]}
|
||||
*/
|
||||
function createMenuTree(parentPageId, pages, pagesOrder, level = 1, currentLevel = 1) {
|
||||
const childrenOrder = pagesOrder.find(order => order.data.page === parentPageId);
|
||||
/**
|
||||
* branch is a page children in tree
|
||||
* if we got some children order on parents tree, then we push found pages in order sequence
|
||||
* otherwise just find all pages includes parent tree
|
||||
*/
|
||||
let ordered = [];
|
||||
if (childrenOrder) {
|
||||
ordered = childrenOrder.order.map((pageId) => {
|
||||
return pages.find(page => page._id === pageId);
|
||||
});
|
||||
}
|
||||
const unordered = pages.filter(page => page._parent === parentPageId);
|
||||
const branch = Array.from(new Set([...ordered, ...unordered]));
|
||||
/**
|
||||
* stop recursion when we got the passed max level
|
||||
*/
|
||||
if (currentLevel === level + 1) {
|
||||
return [];
|
||||
}
|
||||
/**
|
||||
* Each parents children can have subbranches
|
||||
*/
|
||||
return branch.filter(page => page && page._id).map(page => {
|
||||
return Object.assign({
|
||||
children: createMenuTree(page._id, pages, pagesOrder, level, currentLevel + 1)
|
||||
}, page.data);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Middleware for all /page/... routes
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
exports.default = asyncMiddleware_1.default((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
/**
|
||||
* Pages without parent
|
||||
* @type {string}
|
||||
*/
|
||||
const parentIdOfRootPages = '0';
|
||||
try {
|
||||
const pages = yield pages_1.default.getAll();
|
||||
const pagesOrder = yield pagesOrder_1.default.getAll();
|
||||
res.locals.menu = createMenuTree(parentIdOfRootPages, pages, pagesOrder, 2);
|
||||
}
|
||||
catch (error) {
|
||||
console.log('Can not load menu:', error);
|
||||
}
|
||||
next();
|
||||
}));
|
|
@ -1,9 +1,9 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
import Pages from "../../controllers/pages";
|
||||
import PagesOrder from "../../controllers/pagesOrder";
|
||||
import Page from "../../models/page";
|
||||
import asyncMiddleware from "../../utils/asyncMiddleware";
|
||||
import PageOrder from "../../models/pageOrder";
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import Pages from '../../controllers/pages';
|
||||
import PagesOrder from '../../controllers/pagesOrder';
|
||||
import Page from '../../models/page';
|
||||
import asyncMiddleware from '../../utils/asyncMiddleware';
|
||||
import PageOrder from '../../models/pageOrder';
|
||||
|
||||
/**
|
||||
* Process one-level pages list to parent-children list
|
||||
|
@ -14,7 +14,7 @@ import PageOrder from "../../models/pageOrder";
|
|||
* @param {number} level
|
||||
* @param {number} currentLevel
|
||||
*
|
||||
* @return {Page[]}
|
||||
* @returns {Page[]}
|
||||
*/
|
||||
function createMenuTree(parentPageId: string, pages: Page[], pagesOrder: PageOrder[], level = 1, currentLevel = 1): Page[] {
|
||||
const childrenOrder = pagesOrder.find(order => order.data.page === parentPageId);
|
||||
|
@ -47,13 +47,14 @@ function createMenuTree(parentPageId: string, pages: Page[], pagesOrder: PageOrd
|
|||
*/
|
||||
return branch.filter(page => page && page._id).map(page => {
|
||||
return Object.assign({
|
||||
children: createMenuTree(page._id, pages, pagesOrder, level, currentLevel + 1)
|
||||
children: createMenuTree(page._id, pages, pagesOrder, level, currentLevel + 1),
|
||||
}, page.data);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware for all /page/... routes
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
|
@ -61,6 +62,7 @@ function createMenuTree(parentPageId: string, pages: Page[], pagesOrder: PageOrd
|
|||
export default asyncMiddleware(async (req: Request, res: Response, next: NextFunction) => {
|
||||
/**
|
||||
* Pages without parent
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
const parentIdOfRootPages = '0';
|
||||
|
|
|
@ -1,64 +0,0 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const dotenv = __importStar(require("dotenv"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
||||
const users_1 = __importDefault(require("../../controllers/users"));
|
||||
dotenv.config();
|
||||
/**
|
||||
* Middleware for checking jwt token
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
function verifyToken(req, res, next) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const token = req.cookies.authToken;
|
||||
const userDoc = yield users_1.default.get();
|
||||
if (!userDoc || userDoc instanceof Error) {
|
||||
res.locals.isAuthorized = false;
|
||||
next();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const decodedToken = jsonwebtoken_1.default.verify(token, userDoc.passHash + config_1.default.get('secret'));
|
||||
res.locals.isAuthorized = !!decodedToken;
|
||||
}
|
||||
catch (e) {
|
||||
res.locals.isAuthorized = false;
|
||||
}
|
||||
next();
|
||||
});
|
||||
}
|
||||
exports.default = verifyToken;
|
|
@ -1,29 +1,32 @@
|
|||
import * as dotenv from "dotenv";
|
||||
import config from "config";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import jwt from "jsonwebtoken";
|
||||
import Users from "../../controllers/users";
|
||||
import * as dotenv from 'dotenv';
|
||||
import config from 'config';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import Users from '../../controllers/users';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
/**
|
||||
* Middleware for checking jwt token
|
||||
*
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
export default async function verifyToken(req: Request, res: Response, next: NextFunction) {
|
||||
export default async function verifyToken(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const token = req.cookies.authToken;
|
||||
const userDoc = await Users.get();
|
||||
|
||||
if (!userDoc || userDoc instanceof Error) {
|
||||
res.locals.isAuthorized = false;
|
||||
next();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const decodedToken = jwt.verify(token, userDoc.passHash + config.get('secret'));
|
||||
|
||||
res.locals.isAuthorized = !!decodedToken;
|
||||
} catch (e) {
|
||||
res.locals.isAuthorized = false;
|
||||
|
|
|
@ -1,76 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const pages_1 = __importDefault(require("../controllers/pages"));
|
||||
const pagesOrder_1 = __importDefault(require("../controllers/pagesOrder"));
|
||||
const token_1 = __importDefault(require("./middlewares/token"));
|
||||
const locals_1 = __importDefault(require("./middlewares/locals"));
|
||||
const router = express_1.default.Router();
|
||||
/**
|
||||
* Create new page form
|
||||
*/
|
||||
router.get('/page/new', token_1.default, locals_1.default, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
const pagesAvailable = yield pages_1.default.getAll();
|
||||
res.render('pages/form', {
|
||||
pagesAvailable,
|
||||
page: null,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
res.status(404);
|
||||
next(error);
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* Edit page form
|
||||
*/
|
||||
router.get('/page/edit/:id', token_1.default, locals_1.default, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pageId = req.params.id;
|
||||
try {
|
||||
const page = yield pages_1.default.get(pageId);
|
||||
const pagesAvailable = yield pages_1.default.getAllExceptChildren(pageId);
|
||||
const parentsChildrenOrdered = yield pagesOrder_1.default.getOrderedChildren(pagesAvailable, pageId, page._parent, true);
|
||||
res.render('pages/form', {
|
||||
page,
|
||||
parentsChildrenOrdered,
|
||||
pagesAvailable,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
res.status(404);
|
||||
next(error);
|
||||
}
|
||||
}));
|
||||
/**
|
||||
* View page
|
||||
*/
|
||||
router.get('/page/:id', token_1.default, (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pageId = req.params.id;
|
||||
try {
|
||||
const page = yield pages_1.default.get(pageId);
|
||||
const pageParent = yield page.parent;
|
||||
res.render('pages/page', {
|
||||
page,
|
||||
pageParent,
|
||||
config: req.app.locals.config,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
res.status(404);
|
||||
next(error);
|
||||
}
|
||||
}));
|
||||
exports.default = router;
|
|
@ -1,16 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Helper for making async middlewares for express router
|
||||
*
|
||||
* @param fn
|
||||
* @returns {function(*=, *=, *=)}
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
function asyncMiddleware(fn) {
|
||||
return (req, res, next) => {
|
||||
Promise.resolve(fn(req, res, next))
|
||||
.catch(next);
|
||||
};
|
||||
}
|
||||
exports.default = asyncMiddleware;
|
|
@ -1,48 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.random16 = exports.binaryMD5 = void 0;
|
||||
const crypto_1 = __importDefault(require("crypto"));
|
||||
/**
|
||||
*
|
||||
* @param {string} hexStr - input hex string
|
||||
* @returns {string} - output binary string
|
||||
*/
|
||||
function hexToBinary(hexStr) {
|
||||
return (parseInt(hexStr, 16).toString(2))
|
||||
.padStart(8, '0');
|
||||
}
|
||||
/**
|
||||
* Create binary md5
|
||||
*
|
||||
* @param stringToHash - string to hash
|
||||
* @returns {string} - binary hash of argument
|
||||
*/
|
||||
function binaryMD5(stringToHash) {
|
||||
return hexToBinary(crypto_1.default.createHash('md5')
|
||||
.update(stringToHash)
|
||||
.digest('hex'));
|
||||
}
|
||||
exports.binaryMD5 = binaryMD5;
|
||||
/**
|
||||
* Returns 16 random bytes in hex format
|
||||
*
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
function random16() {
|
||||
return new Promise((resolve, reject) => {
|
||||
crypto_1.default.randomBytes(16, (err, raw) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(raw.toString('hex'));
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.random16 = random16;
|
||||
exports.default = {
|
||||
binaryMD5,
|
||||
random16,
|
||||
};
|
|
@ -1,9 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const db = new nedb_1.default({ filename: `./${config_1.default.get('database')}/aliases.db`, autoload: true });
|
||||
exports.default = db;
|
|
@ -1,6 +1,9 @@
|
|||
import Datastore from "nedb";
|
||||
import config from "config";
|
||||
import Datastore from 'nedb';
|
||||
import config from 'config';
|
||||
|
||||
const db = new Datastore({ filename: `./${config.get('database')}/aliases.db`, autoload: true });
|
||||
const db = new Datastore({
|
||||
filename: `./${config.get('database')}/aliases.db`,
|
||||
autoload: true,
|
||||
});
|
||||
|
||||
export default db;
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const db = new nedb_1.default({ filename: `./${config_1.default.get('database')}/files.db`, autoload: true });
|
||||
exports.default = db;
|
|
@ -1,6 +1,9 @@
|
|||
import Datastore from "nedb";
|
||||
import config from "config";
|
||||
import Datastore from 'nedb';
|
||||
import config from 'config';
|
||||
|
||||
const db = new Datastore({ filename: `./${config.get('database')}/files.db`, autoload: true });
|
||||
const db = new Datastore({
|
||||
filename: `./${config.get('database')}/files.db`,
|
||||
autoload: true,
|
||||
});
|
||||
|
||||
export default db;
|
||||
|
|
|
@ -1,167 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Database = void 0;
|
||||
const pages_1 = __importDefault(require("./pages"));
|
||||
const files_1 = __importDefault(require("./files"));
|
||||
const password_1 = __importDefault(require("./password"));
|
||||
const aliases_1 = __importDefault(require("./aliases"));
|
||||
const pagesOrder_1 = __importDefault(require("./pagesOrder"));
|
||||
/**
|
||||
* @class Database
|
||||
* @classdesc Simple decorator class to work with nedb datastore
|
||||
*
|
||||
* @property db - nedb Datastore object
|
||||
*/
|
||||
class Database {
|
||||
/**
|
||||
* @constructor
|
||||
*
|
||||
* @param {Object} nedbInstance - nedb Datastore object
|
||||
*/
|
||||
constructor(nedbInstance) {
|
||||
this.db = nedbInstance;
|
||||
}
|
||||
/**
|
||||
* Insert new document into the database
|
||||
* @see https://github.com/louischatriot/nedb#inserting-documents
|
||||
*
|
||||
* @param {Object} doc - object to insert
|
||||
* @returns {Promise<Object|Error>} - inserted doc or Error object
|
||||
*/
|
||||
insert(doc) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return new Promise((resolve, reject) => this.db.insert(doc, (err, newDoc) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(newDoc);
|
||||
}));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find documents that match passed query
|
||||
* @see https://github.com/louischatriot/nedb#finding-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} projection - projection object
|
||||
* @returns {Promise<Array<Object>|Error>} - found docs or Error object
|
||||
*/
|
||||
find(query, projection) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const cbk = (resolve, reject) => (err, docs) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(docs);
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
if (projection) {
|
||||
this.db.find(query, projection, cbk(resolve, reject));
|
||||
}
|
||||
else {
|
||||
this.db.find(query, cbk(resolve, reject));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Find one document matches passed query
|
||||
* @see https://github.com/louischatriot/nedb#finding-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} projection - projection object
|
||||
* @returns {Promise<Object|Error>} - found doc or Error object
|
||||
*/
|
||||
findOne(query, projection) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const cbk = (resolve, reject) => (err, doc) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(doc);
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
if (projection) {
|
||||
this.db.findOne(query, projection, cbk(resolve, reject));
|
||||
}
|
||||
else {
|
||||
this.db.findOne(query, cbk(resolve, reject));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Update document matches query
|
||||
* @see https://github.com/louischatriot/nedb#updating-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} update - fields to update
|
||||
* @param {Object} options
|
||||
* @param {Boolean} options.multi - (false) allows update several documents
|
||||
* @param {Boolean} options.upsert - (false) if true, upsert document with update fields.
|
||||
* Method will return inserted doc or number of affected docs if doc hasn't been inserted
|
||||
* @param {Boolean} options.returnUpdatedDocs - (false) if true, returns affected docs
|
||||
* @returns {Promise<number|Object|Object[]|Error>} - number of updated rows or affected docs or Error object
|
||||
*/
|
||||
update(query, update, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return new Promise((resolve, reject) => this.db.update(query, update, options, (err, result, affectedDocs) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
switch (true) {
|
||||
case options.returnUpdatedDocs:
|
||||
resolve(affectedDocs);
|
||||
break;
|
||||
case options.upsert:
|
||||
if (affectedDocs) {
|
||||
resolve(affectedDocs);
|
||||
}
|
||||
resolve(result);
|
||||
break;
|
||||
default:
|
||||
resolve(result);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Remove document matches passed query
|
||||
* @see https://github.com/louischatriot/nedb#removing-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} options
|
||||
* @param {Boolean} options.multi - (false) if true, remove several docs
|
||||
* @returns {Promise<number|Error>} - number of removed rows or Error object
|
||||
*/
|
||||
remove(query, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return new Promise((resolve, reject) => this.db.remove(query, options, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(result);
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Database = Database;
|
||||
exports.default = {
|
||||
pages: new Database(pages_1.default),
|
||||
password: new Database(password_1.default),
|
||||
aliases: new Database(aliases_1.default),
|
||||
pagesOrder: new Database(pagesOrder_1.default),
|
||||
files: new Database(files_1.default)
|
||||
};
|
|
@ -1,9 +1,9 @@
|
|||
import pages from "./pages";
|
||||
import files from "./files";
|
||||
import password from "./password";
|
||||
import aliases from "./aliases";
|
||||
import pagesOrder from "./pagesOrder";
|
||||
import Datastore from "nedb";
|
||||
import pages from './pages';
|
||||
import files from './files';
|
||||
import password from './password';
|
||||
import aliases from './aliases';
|
||||
import pagesOrder from './pagesOrder';
|
||||
import Datastore from 'nedb';
|
||||
|
||||
interface Options {
|
||||
upsert?: boolean;
|
||||
|
@ -18,9 +18,9 @@ interface Options {
|
|||
* @property db - nedb Datastore object
|
||||
*/
|
||||
export class Database {
|
||||
db: Datastore;
|
||||
private db: Datastore;
|
||||
/**
|
||||
* @constructor
|
||||
* @class
|
||||
*
|
||||
* @param {Object} nedbInstance - nedb Datastore object
|
||||
*/
|
||||
|
@ -30,12 +30,13 @@ export class Database {
|
|||
|
||||
/**
|
||||
* Insert new document into the database
|
||||
*
|
||||
* @see https://github.com/louischatriot/nedb#inserting-documents
|
||||
*
|
||||
* @param {Object} doc - object to insert
|
||||
* @returns {Promise<Object|Error>} - inserted doc or Error object
|
||||
*/
|
||||
async insert(doc: object): Promise<object | Error> {
|
||||
public async insert(doc: object): Promise<object | Error> {
|
||||
return new Promise((resolve, reject) => this.db.insert(doc, (err, newDoc) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
|
@ -47,13 +48,14 @@ export class Database {
|
|||
|
||||
/**
|
||||
* Find documents that match passed query
|
||||
*
|
||||
* @see https://github.com/louischatriot/nedb#finding-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} projection - projection object
|
||||
* @returns {Promise<Array<Object>|Error>} - found docs or Error object
|
||||
*/
|
||||
async find(query: object, projection?: object): Promise<Array<object> | Error> {
|
||||
public async find(query: object, projection?: object): Promise<Array<object> | Error> {
|
||||
const cbk = (resolve: Function, reject: Function) => (err: Error | null, docs: any[]) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
|
@ -73,13 +75,14 @@ export class Database {
|
|||
|
||||
/**
|
||||
* Find one document matches passed query
|
||||
*
|
||||
* @see https://github.com/louischatriot/nedb#finding-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} projection - projection object
|
||||
* @returns {Promise<Object|Error>} - found doc or Error object
|
||||
*/
|
||||
async findOne(query: object, projection?: object): Promise<object | Error> {
|
||||
public async findOne(query: object, projection?: object): Promise<object | Error> {
|
||||
const cbk = (resolve: Function, reject: Function) => (err: Error | null, doc: any) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
|
@ -99,18 +102,19 @@ export class Database {
|
|||
|
||||
/**
|
||||
* Update document matches query
|
||||
*
|
||||
* @see https://github.com/louischatriot/nedb#updating-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} update - fields to update
|
||||
* @param {Object} options
|
||||
* @param {Boolean} options.multi - (false) allows update several documents
|
||||
* @param {Boolean} options.upsert - (false) if true, upsert document with update fields.
|
||||
* @param {boolean} options.multi - (false) allows update several documents
|
||||
* @param {boolean} options.upsert - (false) if true, upsert document with update fields.
|
||||
* Method will return inserted doc or number of affected docs if doc hasn't been inserted
|
||||
* @param {Boolean} options.returnUpdatedDocs - (false) if true, returns affected docs
|
||||
* @param {boolean} options.returnUpdatedDocs - (false) if true, returns affected docs
|
||||
* @returns {Promise<number|Object|Object[]|Error>} - number of updated rows or affected docs or Error object
|
||||
*/
|
||||
async update(query: object, update: object, options: Options = {}) {
|
||||
public async update(query: object, update: object, options: Options = {}): Promise<any> {
|
||||
return new Promise((resolve, reject) => this.db.update(query, update, options, (err, result, affectedDocs) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
|
@ -134,14 +138,15 @@ export class Database {
|
|||
|
||||
/**
|
||||
* Remove document matches passed query
|
||||
*
|
||||
* @see https://github.com/louischatriot/nedb#removing-documents
|
||||
*
|
||||
* @param {Object} query - query object
|
||||
* @param {Object} options
|
||||
* @param {Boolean} options.multi - (false) if true, remove several docs
|
||||
* @param {boolean} options.multi - (false) if true, remove several docs
|
||||
* @returns {Promise<number|Error>} - number of removed rows or Error object
|
||||
*/
|
||||
async remove(query: object, options = {}) {
|
||||
public async remove(query: object, options = {}): Promise<number|Error> {
|
||||
return new Promise((resolve, reject) => this.db.remove(query, options, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
|
@ -157,5 +162,5 @@ export default {
|
|||
password: new Database(password),
|
||||
aliases: new Database(aliases),
|
||||
pagesOrder: new Database(pagesOrder),
|
||||
files: new Database(files)
|
||||
files: new Database(files),
|
||||
};
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const db = new nedb_1.default({ filename: `./${config_1.default.get('database')}/pages.db`, autoload: true });
|
||||
exports.default = db;
|
|
@ -1,6 +1,9 @@
|
|||
import Datastore from "nedb";
|
||||
import config from "config";
|
||||
import Datastore from 'nedb';
|
||||
import config from 'config';
|
||||
|
||||
const db = new Datastore({ filename: `./${config.get('database')}/pages.db`, autoload: true });
|
||||
const db = new Datastore({
|
||||
filename: `./${config.get('database')}/pages.db`,
|
||||
autoload: true,
|
||||
});
|
||||
|
||||
export default db;
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const db = new nedb_1.default({ filename: `./${config_1.default.get('database')}/pagesOrder.db`, autoload: true });
|
||||
exports.default = db;
|
|
@ -1,5 +1,8 @@
|
|||
import Datastore from "nedb";
|
||||
import config from "config";
|
||||
const db = new Datastore({ filename: `./${config.get('database')}/pagesOrder.db`, autoload: true });
|
||||
import Datastore from 'nedb';
|
||||
import config from 'config';
|
||||
const db = new Datastore({
|
||||
filename: `./${config.get('database')}/pagesOrder.db`,
|
||||
autoload: true,
|
||||
});
|
||||
|
||||
export default db;
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const db = new nedb_1.default({ filename: `./${config_1.default.get('database')}/password.db`, autoload: true });
|
||||
exports.default = db;
|
|
@ -1,6 +1,9 @@
|
|||
import Datastore from "nedb";
|
||||
import config from "config";
|
||||
import Datastore from 'nedb';
|
||||
import config from 'config';
|
||||
|
||||
const db = new Datastore({ filename: `./${config.get('database')}/password.db`, autoload: true });
|
||||
const db = new Datastore({
|
||||
filename: `./${config.get('database')}/password.db`,
|
||||
autoload: true,
|
||||
});
|
||||
|
||||
export default db;
|
||||
|
|
|
@ -1,31 +0,0 @@
|
|||
"use strict";
|
||||
/**
|
||||
* Merge to objects recursively
|
||||
*
|
||||
* @param {object} target
|
||||
* @param {object[]} sources
|
||||
* @returns {object}
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function deepMerge(target, ...sources) {
|
||||
const isObject = (item) => item && typeof item === 'object' && !Array.isArray(item);
|
||||
if (!sources.length) {
|
||||
return target;
|
||||
}
|
||||
const source = sources.shift();
|
||||
if (isObject(target) && isObject(source)) {
|
||||
for (const key in source) {
|
||||
if (isObject(source[key])) {
|
||||
if (!target[key]) {
|
||||
Object.assign(target, { [key]: {} });
|
||||
}
|
||||
deepMerge(target[key], source[key]);
|
||||
}
|
||||
else {
|
||||
Object.assign(target, { [key]: source[key] });
|
||||
}
|
||||
}
|
||||
}
|
||||
return deepMerge(target, ...sources);
|
||||
}
|
||||
exports.default = deepMerge;
|
|
@ -6,8 +6,12 @@
|
|||
* @returns {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param target
|
||||
* @param {...any} sources
|
||||
*/
|
||||
function deepMerge(target: any, ...sources: any[]): object {
|
||||
const isObject = (item: any) => item && typeof item === 'object' && !Array.isArray(item);
|
||||
const isObject = (item: any): boolean => item && typeof item === 'object' && !Array.isArray(item);
|
||||
|
||||
if (!sources.length) {
|
||||
return target;
|
||||
|
|
|
@ -1,96 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const rcPath = path_1.default.resolve(__dirname, '../../', config_1.default.get('rcFile') || './.codexdocsrc');
|
||||
/**
|
||||
* @typedef {object} RCData
|
||||
* @property {string} title - website title
|
||||
* @property {object[]} menu - options for website menu
|
||||
* @property {string} menu[].title - menu option title
|
||||
* @property {string} menu[].uri - menu option href
|
||||
*/
|
||||
/**
|
||||
* @class RCParser
|
||||
* @classdesc Class to parse runtime configuration file for CodeX Docs engine
|
||||
*/
|
||||
class RCParser {
|
||||
/**
|
||||
* Default CodeX Docs configuration
|
||||
*
|
||||
* @static
|
||||
* @returns {{title: string, menu: Array}}
|
||||
*/
|
||||
static get DEFAULTS() {
|
||||
return {
|
||||
title: 'CodeX Docs',
|
||||
menu: [],
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Find and parse runtime configuration file
|
||||
*
|
||||
* @static
|
||||
* @returns {{title: string, menu: []}}
|
||||
*/
|
||||
static getConfiguration() {
|
||||
if (!fs_1.default.existsSync(rcPath)) {
|
||||
return RCParser.DEFAULTS;
|
||||
}
|
||||
const file = fs_1.default.readFileSync(rcPath, 'utf-8');
|
||||
const rConfig = RCParser.DEFAULTS;
|
||||
let userConfig;
|
||||
try {
|
||||
userConfig = JSON.parse(file);
|
||||
}
|
||||
catch (e) {
|
||||
console.log('CodeX Docs rc file should be in JSON format.');
|
||||
return RCParser.DEFAULTS;
|
||||
}
|
||||
for (const option in userConfig) {
|
||||
if (Object.prototype.hasOwnProperty.call(userConfig, option)) {
|
||||
rConfig[option] = userConfig[option] || RCParser.DEFAULTS[option] || undefined;
|
||||
}
|
||||
}
|
||||
if (!(rConfig.menu instanceof Array)) {
|
||||
console.log('Menu section in the rc file must be an array.');
|
||||
rConfig.menu = RCParser.DEFAULTS.menu;
|
||||
}
|
||||
rConfig.menu = rConfig.menu.filter((option, i) => {
|
||||
i = i + 1;
|
||||
if (typeof option === 'string') {
|
||||
return true;
|
||||
}
|
||||
if (!option || option instanceof Array || typeof option !== 'object') {
|
||||
console.log(`Menu option #${i} in rc file must be a string or an object`);
|
||||
return false;
|
||||
}
|
||||
const { title, uri } = option;
|
||||
if (!title || typeof title !== 'string') {
|
||||
console.log(`Menu option #${i} title must be a string.`);
|
||||
return false;
|
||||
}
|
||||
if (!uri || typeof uri !== 'string') {
|
||||
console.log(`Menu option #${i} uri must be a string.`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
rConfig.menu = rConfig.menu.map((option) => {
|
||||
if (typeof option === 'string') {
|
||||
return {
|
||||
title: option,
|
||||
/* Replace all non alpha- and numeric-symbols with '-' */
|
||||
uri: '/' + option.toLowerCase().replace(/[ -/:-@[-`{-~]+/, '-'),
|
||||
};
|
||||
}
|
||||
return option;
|
||||
});
|
||||
return rConfig;
|
||||
}
|
||||
}
|
||||
exports.default = RCParser;
|
|
@ -27,7 +27,7 @@ export default class RCParser {
|
|||
* @static
|
||||
* @returns {{title: string, menu: Array}}
|
||||
*/
|
||||
static get DEFAULTS():RConfig {
|
||||
public static get DEFAULTS():RConfig {
|
||||
return {
|
||||
title: 'CodeX Docs',
|
||||
menu: [],
|
||||
|
@ -40,7 +40,7 @@ export default class RCParser {
|
|||
* @static
|
||||
* @returns {{title: string, menu: []}}
|
||||
*/
|
||||
static getConfiguration(): RConfig {
|
||||
public static getConfiguration(): RConfig {
|
||||
if (!fs.existsSync(rcPath)) {
|
||||
return RCParser.DEFAULTS;
|
||||
}
|
||||
|
|
|
@ -1,83 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const translationTable = {
|
||||
а: 'a',
|
||||
б: 'b',
|
||||
в: 'v',
|
||||
г: 'g',
|
||||
д: 'd',
|
||||
е: 'e',
|
||||
ж: 'g',
|
||||
з: 'z',
|
||||
и: 'i',
|
||||
й: 'y',
|
||||
к: 'k',
|
||||
л: 'l',
|
||||
м: 'm',
|
||||
н: 'n',
|
||||
о: 'o',
|
||||
п: 'p',
|
||||
р: 'r',
|
||||
с: 's',
|
||||
т: 't',
|
||||
у: 'u',
|
||||
ф: 'f',
|
||||
ы: 'i',
|
||||
э: 'e',
|
||||
А: 'A',
|
||||
Б: 'B',
|
||||
В: 'V',
|
||||
Г: 'G',
|
||||
Д: 'D',
|
||||
Е: 'E',
|
||||
Ж: 'G',
|
||||
З: 'Z',
|
||||
И: 'I',
|
||||
Й: 'Y',
|
||||
К: 'K',
|
||||
Л: 'L',
|
||||
М: 'M',
|
||||
Н: 'N',
|
||||
О: 'O',
|
||||
П: 'P',
|
||||
Р: 'R',
|
||||
С: 'S',
|
||||
Т: 'T',
|
||||
У: 'U',
|
||||
Ф: 'F',
|
||||
Ы: 'I',
|
||||
Э: 'E',
|
||||
ё: 'yo',
|
||||
х: 'h',
|
||||
ц: 'ts',
|
||||
ч: 'ch',
|
||||
ш: 'sh',
|
||||
щ: 'shch',
|
||||
ъ: "''",
|
||||
ь: "'",
|
||||
ю: 'yu',
|
||||
я: 'ya',
|
||||
Ё: 'YO',
|
||||
Х: 'H',
|
||||
Ц: 'TS',
|
||||
Ч: 'CH',
|
||||
Ш: 'SH',
|
||||
Щ: 'SHCH',
|
||||
Ъ: "''",
|
||||
Ь: "'",
|
||||
Ю: 'YU',
|
||||
Я: 'YA',
|
||||
};
|
||||
/**
|
||||
* Function to translate string
|
||||
*
|
||||
* @param string - string to translate
|
||||
* @returns {string} - translated string
|
||||
*/
|
||||
/**
|
||||
* @param string
|
||||
*/
|
||||
function translateString(string) {
|
||||
return string.replace(/[А-яёЁ]/g, (char) => translationTable[char] || char);
|
||||
}
|
||||
exports.default = translateString;
|
|
@ -1,49 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Twig extensions
|
||||
*/
|
||||
const twig_1 = __importDefault(require("twig"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const urlify_1 = __importDefault(require("./urlify"));
|
||||
exports.default = (function () {
|
||||
'use strict';
|
||||
/**
|
||||
* Function for include svg on page
|
||||
*
|
||||
* @example svg('path/from/root/dir')
|
||||
* @param {string} filename - name of icon
|
||||
* @returns {string} - svg code
|
||||
*/
|
||||
twig_1.default.extendFunction('svg', function (filename) {
|
||||
return fs_1.default.readFileSync(`${__dirname}/../frontend/svg/${filename}.svg`, 'utf-8');
|
||||
});
|
||||
/**
|
||||
* Convert text to URL-like string
|
||||
* Example: "What is <mark>clean data</mark>" -> "what-is-clean-data"
|
||||
*
|
||||
* @param {string} string - source string with HTML
|
||||
* @returns {string} alias-like string
|
||||
*/
|
||||
twig_1.default.extendFilter('urlify', function (string) {
|
||||
return urlify_1.default(string);
|
||||
});
|
||||
/**
|
||||
* Parse link as URL object
|
||||
*
|
||||
* @param {string} linkUrl - link to be processed
|
||||
* @returns {UrlWithStringQuery} — url data
|
||||
*/
|
||||
twig_1.default.extendFunction('parseLink', function (linkUrl) {
|
||||
try {
|
||||
return new URL(linkUrl).toString();
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
return '';
|
||||
}
|
||||
});
|
||||
}());
|
|
@ -1,31 +0,0 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const translation_1 = __importDefault(require("./translation"));
|
||||
/**
|
||||
* Convert text to URL-like string
|
||||
* Example: "What is <mark>clean data</mark>" -> "what-is-clean-data"
|
||||
*
|
||||
* @param {string} string - source string with HTML
|
||||
* @returns {string} alias-like string
|
||||
*/
|
||||
function urlify(string) {
|
||||
// strip tags
|
||||
string = string.replace(/(<([^>]+)>)/ig, '');
|
||||
// remove nbsp
|
||||
string = string.replace(/ /g, ' ');
|
||||
// remove all symbols except chars
|
||||
string = string.replace(/[^a-zA-Z0-9А-Яа-яЁё ]/g, ' ');
|
||||
// remove whitespaces
|
||||
string = string.replace(/ +/g, ' ').trim();
|
||||
// lowercase
|
||||
string = string.toLowerCase();
|
||||
// join words with hyphens
|
||||
string = string.split(' ').join('-');
|
||||
// translate
|
||||
string = translation_1.default(string);
|
||||
return string;
|
||||
}
|
||||
exports.default = urlify;
|
148
test/database.js
148
test/database.js
|
@ -1,148 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const chai_1 = require("chai");
|
||||
const nedb_1 = __importDefault(require("nedb"));
|
||||
const database_1 = require("../src/utils/database");
|
||||
describe('Database', () => {
|
||||
const pathToDB = `./${config_1.default.get('database')}/test.db`;
|
||||
let nedbInstance;
|
||||
let db;
|
||||
before(() => {
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
it('Creating db instance', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
nedbInstance = new nedb_1.default({ filename: pathToDB, autoload: true });
|
||||
db = new database_1.Database(nedbInstance);
|
||||
}));
|
||||
it('Inserting document', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data = 'Text data';
|
||||
const insertedDoc = yield db.insert({ data });
|
||||
chai_1.expect(insertedDoc).to.be.a('object');
|
||||
chai_1.expect(insertedDoc.data).to.equal(data);
|
||||
}));
|
||||
it('Finding document', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data = 'Text data';
|
||||
const insertedDoc = yield db.insert({ data });
|
||||
chai_1.expect(insertedDoc).to.be.a('object');
|
||||
chai_1.expect(insertedDoc.data).to.equal(data);
|
||||
const foundDoc = yield db.findOne({ _id: insertedDoc._id });
|
||||
chai_1.expect(foundDoc).not.be.null;
|
||||
chai_1.expect(foundDoc._id).to.equal(insertedDoc._id);
|
||||
chai_1.expect(foundDoc.data).to.equal(data);
|
||||
const projectedDoc = yield db.findOne({ _id: insertedDoc._id }, { data: 1, _id: 0 });
|
||||
chai_1.expect(Object.keys(projectedDoc).length).to.equal(1);
|
||||
chai_1.expect(Object.keys(projectedDoc).pop()).to.equal('data');
|
||||
}));
|
||||
it('Updating document', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data = 'Text data';
|
||||
const insertedDoc = yield db.insert({ data });
|
||||
chai_1.expect(insertedDoc).to.be.a('object');
|
||||
chai_1.expect(insertedDoc.data).to.equal(data);
|
||||
const updatedData = 'Updated text data';
|
||||
yield db.update({ _id: insertedDoc._id }, { data: updatedData });
|
||||
const updatedDoc = yield db.findOne({ _id: insertedDoc._id });
|
||||
chai_1.expect(updatedDoc).not.be.null;
|
||||
chai_1.expect(updatedDoc.data).not.equal(data);
|
||||
chai_1.expect(updatedDoc.data).to.equal(updatedData);
|
||||
}));
|
||||
it('Updating documents with options', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data = { update: true, data: 'Text data' };
|
||||
yield db.insert(data);
|
||||
yield db.insert(data);
|
||||
let numberOfUpdatedDocs = yield db.update({ update: true }, { $set: { data: 'First update' } }, { multi: true });
|
||||
chai_1.expect(numberOfUpdatedDocs).to.equal(2);
|
||||
const affectedDocs = yield db.update({ update: true }, { $set: { data: 'Second update' } }, { multi: true, returnUpdatedDocs: true });
|
||||
chai_1.expect(affectedDocs).to.be.a('array');
|
||||
affectedDocs.forEach((doc) => {
|
||||
chai_1.expect(doc.data).to.equal('Second update');
|
||||
});
|
||||
const upsertedDoc = yield db.update({ update: true, data: 'First update' }, { $set: { data: 'Third update' } }, { upsert: true });
|
||||
chai_1.expect(upsertedDoc.update).to.be.true;
|
||||
chai_1.expect(upsertedDoc.data).to.equal('Third update');
|
||||
numberOfUpdatedDocs = yield db.update({ data: 'Third update' }, { $set: { data: 'Fourth update' } }, { upsert: true });
|
||||
chai_1.expect(numberOfUpdatedDocs).to.equal(1);
|
||||
}));
|
||||
it('Finding documents', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data1 = 'Text data 1';
|
||||
const data2 = 'Text data 2';
|
||||
const insertedDoc1 = yield db.insert({ data: data1, flag: true, no: 1 });
|
||||
const insertedDoc2 = yield db.insert({ data: data2, flag: true, no: 2 });
|
||||
const foundDocs = yield db.find({ flag: true });
|
||||
chai_1.expect(foundDocs).to.be.a('array');
|
||||
chai_1.expect(foundDocs.length).to.equal(2);
|
||||
foundDocs.sort(({ no: a }, { no: b }) => a - b);
|
||||
chai_1.expect(foundDocs[0]._id).to.equal(insertedDoc1._id);
|
||||
chai_1.expect(foundDocs[0].data).to.equal(insertedDoc1.data);
|
||||
chai_1.expect(foundDocs[1]._id).to.equal(insertedDoc2._id);
|
||||
chai_1.expect(foundDocs[1].data).to.equal(insertedDoc2.data);
|
||||
const projectedDocs = yield db.find({ flag: true }, { no: 1, _id: 0 });
|
||||
chai_1.expect(projectedDocs.length).to.equal(2);
|
||||
projectedDocs.forEach(data => {
|
||||
chai_1.expect(Object.keys(data).length).to.equal(1);
|
||||
chai_1.expect(Object.keys(data).pop()).to.equal('no');
|
||||
});
|
||||
}));
|
||||
it('Removing document', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const data = 'Text data';
|
||||
const insertedDoc = yield db.insert({ data });
|
||||
chai_1.expect(insertedDoc).to.be.a('object');
|
||||
chai_1.expect(insertedDoc.data).to.equal(data);
|
||||
yield db.remove({ _id: insertedDoc._id });
|
||||
const deletedDoc = yield db.findOne({ _id: insertedDoc._id });
|
||||
chai_1.expect(deletedDoc).to.be.null;
|
||||
}));
|
||||
it('Test invalid database queries', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
try {
|
||||
yield db.insert({});
|
||||
}
|
||||
catch (err) {
|
||||
chai_1.expect(err.message).to.equal('Cannot read property \'_id\' of undefined');
|
||||
}
|
||||
try {
|
||||
yield db.find({ size: { $invalidComparator: 1 } });
|
||||
}
|
||||
catch (err) {
|
||||
chai_1.expect(err.message).to.equal('Unknown comparison function $invalidComparator');
|
||||
}
|
||||
try {
|
||||
yield db.findOne({ field: { $invalidComparator: 1 } });
|
||||
}
|
||||
catch (err) {
|
||||
chai_1.expect(err.message).to.equal('Unknown comparison function $invalidComparator');
|
||||
}
|
||||
try {
|
||||
// await db.update({field: {$undefinedComparator: 1}});
|
||||
throw new Error('Unknown comparison function $undefinedComparator');
|
||||
}
|
||||
catch (err) {
|
||||
chai_1.expect(err.message).to.equal('Unknown comparison function $undefinedComparator');
|
||||
}
|
||||
try {
|
||||
yield db.remove({ field: { $undefinedComparator: 1 } });
|
||||
}
|
||||
catch (err) {
|
||||
chai_1.expect(err.message).to.equal('Unknown comparison function $undefinedComparator');
|
||||
}
|
||||
}));
|
||||
after(() => {
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
});
|
|
@ -1,46 +0,0 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const server_1 = __importDefault(require("../bin/server"));
|
||||
const chai_http_1 = __importDefault(require("chai-http"));
|
||||
const chai_1 = __importStar(require("chai"));
|
||||
const app = server_1.default.app;
|
||||
chai_1.default.use(chai_http_1.default);
|
||||
describe('Express app', () => {
|
||||
it('App is available', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const agent = chai_1.default.request.agent(app);
|
||||
const result = yield agent
|
||||
.get('/');
|
||||
chai_1.expect(result).to.have.status(200);
|
||||
}));
|
||||
});
|
|
@ -1,121 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chai_1 = require("chai");
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const alias_1 = __importDefault(require("../../src/models/alias"));
|
||||
const crypto_1 = require("../../src/utils/crypto");
|
||||
const database_1 = __importDefault(require("../../src/utils/database"));
|
||||
const aliases = database_1.default['aliases'];
|
||||
describe('Alias model', () => {
|
||||
after(() => {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './aliases.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
it('Working with empty model', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let alias = new alias_1.default();
|
||||
chai_1.expect(alias.data).to.be.a('object');
|
||||
let { data } = alias;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.hash).to.be.undefined;
|
||||
chai_1.expect(data.type).to.be.undefined;
|
||||
chai_1.expect(data.deprecated).to.be.false;
|
||||
chai_1.expect(data.id).to.be.undefined;
|
||||
alias = new alias_1.default();
|
||||
data = alias.data;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.hash).to.be.undefined;
|
||||
chai_1.expect(data.type).to.be.undefined;
|
||||
chai_1.expect(data.deprecated).to.be.false;
|
||||
chai_1.expect(data.id).to.be.undefined;
|
||||
const initialData = {
|
||||
_id: 'alias_id',
|
||||
type: alias_1.default.types.PAGE,
|
||||
id: 'page_id'
|
||||
};
|
||||
const aliasName = 'alias name';
|
||||
alias = new alias_1.default(initialData, aliasName);
|
||||
data = alias.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.hash).to.equal(crypto_1.binaryMD5(aliasName));
|
||||
chai_1.expect(data.type).to.equal(initialData.type);
|
||||
chai_1.expect(data.deprecated).to.equal(false);
|
||||
const update = {
|
||||
type: alias_1.default.types.PAGE,
|
||||
id: 'page_id',
|
||||
hash: crypto_1.binaryMD5('another test hash'),
|
||||
deprecated: true
|
||||
};
|
||||
alias.data = update;
|
||||
data = alias.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.type).to.equal(update.type);
|
||||
chai_1.expect(data.hash).to.equal(update.hash);
|
||||
chai_1.expect(data.deprecated).to.equal(update.deprecated);
|
||||
}));
|
||||
it('Static get method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
type: alias_1.default.types.PAGE,
|
||||
id: 'page_id'
|
||||
};
|
||||
const aliasName = 'alias name';
|
||||
const alias = new alias_1.default(initialData, aliasName);
|
||||
const savedAlias = yield alias.save();
|
||||
const foundAlias = yield alias_1.default.get(aliasName);
|
||||
const { data } = foundAlias;
|
||||
chai_1.expect(data._id).to.equal(savedAlias._id);
|
||||
chai_1.expect(data.hash).to.equal(crypto_1.binaryMD5(aliasName));
|
||||
chai_1.expect(data.type).to.equal(initialData.type);
|
||||
chai_1.expect(data.deprecated).to.equal(false);
|
||||
}));
|
||||
it('Saving, updating and deleting model in the database', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
type: alias_1.default.types.PAGE,
|
||||
id: 'page_id'
|
||||
};
|
||||
const aliasName = 'alias name';
|
||||
const alias = new alias_1.default(initialData, aliasName);
|
||||
const savedAlias = yield alias.save();
|
||||
chai_1.expect(savedAlias._id).not.be.undefined;
|
||||
chai_1.expect(savedAlias.hash).to.equal(crypto_1.binaryMD5(aliasName));
|
||||
chai_1.expect(savedAlias.type).to.equal(initialData.type);
|
||||
chai_1.expect(savedAlias.id).to.equal(initialData.id);
|
||||
chai_1.expect(savedAlias.deprecated).to.equal(false);
|
||||
const insertedAlias = yield aliases.findOne({ _id: savedAlias._id });
|
||||
chai_1.expect(insertedAlias._id).to.equal(savedAlias._id);
|
||||
chai_1.expect(insertedAlias.hash).to.equal(savedAlias.hash);
|
||||
chai_1.expect(insertedAlias.type).to.equal(savedAlias.type);
|
||||
chai_1.expect(insertedAlias.id).to.equal(savedAlias.id);
|
||||
chai_1.expect(insertedAlias.deprecated).to.equal(savedAlias.deprecated);
|
||||
const updateData = {
|
||||
type: alias_1.default.types.PAGE,
|
||||
id: 'page_id',
|
||||
hash: crypto_1.binaryMD5('another test hash'),
|
||||
deprecated: true
|
||||
};
|
||||
alias.data = updateData;
|
||||
yield alias.save();
|
||||
chai_1.expect(alias._id).to.equal(insertedAlias._id);
|
||||
const updatedAlias = yield aliases.findOne({ _id: alias._id });
|
||||
chai_1.expect(updatedAlias._id).to.equal(savedAlias._id);
|
||||
chai_1.expect(updatedAlias.hash).to.equal(updateData.hash);
|
||||
chai_1.expect(updatedAlias.type).to.equal(updateData.type);
|
||||
chai_1.expect(updatedAlias.id).to.equal(updateData.id);
|
||||
chai_1.expect(updatedAlias.deprecated).to.equal(updateData.deprecated);
|
||||
}));
|
||||
});
|
|
@ -1,199 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chai_1 = require("chai");
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const file_1 = __importDefault(require("../../src/models/file"));
|
||||
const database_1 = __importDefault(require("../../src/utils/database"));
|
||||
const files = database_1.default['files'];
|
||||
describe('File model', () => {
|
||||
after(() => {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './files.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
it('Working with empty model', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let file = new file_1.default();
|
||||
chai_1.expect(file.data).to.be.a('object');
|
||||
let { data } = file;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.name).to.be.undefined;
|
||||
chai_1.expect(data.filename).to.be.undefined;
|
||||
chai_1.expect(data.path).to.be.undefined;
|
||||
chai_1.expect(data.size).to.be.undefined;
|
||||
chai_1.expect(data.mimetype).to.be.undefined;
|
||||
file = new file_1.default();
|
||||
data = file.data;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.name).to.be.undefined;
|
||||
chai_1.expect(data.filename).to.be.undefined;
|
||||
chai_1.expect(data.path).to.be.undefined;
|
||||
chai_1.expect(data.size).to.be.undefined;
|
||||
chai_1.expect(data.mimetype).to.be.undefined;
|
||||
const initialData = {
|
||||
_id: 'file_id',
|
||||
name: 'filename',
|
||||
filename: 'randomname',
|
||||
path: '/uploads/randomname',
|
||||
size: 1024,
|
||||
mimetype: 'image/png'
|
||||
};
|
||||
file = new file_1.default(initialData);
|
||||
// const json = file.toJSON();
|
||||
data = file.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.name).to.equal(initialData.name);
|
||||
chai_1.expect(data.filename).to.equal(initialData.filename);
|
||||
chai_1.expect(data.path).to.equal(initialData.path);
|
||||
chai_1.expect(data.size).to.equal(initialData.size);
|
||||
chai_1.expect(data.mimetype).to.equal(initialData.mimetype);
|
||||
const update = {
|
||||
_id: '12345',
|
||||
name: 'updated filename',
|
||||
filename: 'updated randomname',
|
||||
path: '/uploads/updated randomname',
|
||||
size: 2048,
|
||||
mimetype: 'image/jpeg'
|
||||
};
|
||||
file.data = update;
|
||||
data = file.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.name).to.equal(update.name);
|
||||
chai_1.expect(data.filename).to.equal(update.filename);
|
||||
chai_1.expect(data.path).to.equal(update.path);
|
||||
chai_1.expect(data.size).to.equal(update.size);
|
||||
chai_1.expect(data.mimetype).to.equal(update.mimetype);
|
||||
}));
|
||||
it('Saving, updating and deleting model in the database', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
name: 'filename',
|
||||
filename: 'randomname',
|
||||
path: '/uploads/randomname',
|
||||
size: 1024,
|
||||
mimetype: 'image/png'
|
||||
};
|
||||
const file = new file_1.default(initialData);
|
||||
const savedFile = yield file.save();
|
||||
chai_1.expect(savedFile._id).not.be.undefined;
|
||||
chai_1.expect(savedFile.name).to.equal(initialData.name);
|
||||
chai_1.expect(savedFile.filename).to.equal(initialData.filename);
|
||||
chai_1.expect(savedFile.path).to.equal(initialData.path);
|
||||
chai_1.expect(savedFile.size).to.equal(initialData.size);
|
||||
chai_1.expect(savedFile.mimetype).to.equal(initialData.mimetype);
|
||||
const insertedFile = yield files.findOne({ _id: file._id });
|
||||
chai_1.expect(insertedFile._id).to.equal(file._id);
|
||||
chai_1.expect(insertedFile.name).to.equal(file.name);
|
||||
chai_1.expect(insertedFile.filename).to.equal(file.filename);
|
||||
chai_1.expect(insertedFile.path).to.equal(file.path);
|
||||
chai_1.expect(insertedFile.size).to.equal(file.size);
|
||||
chai_1.expect(insertedFile.mimetype).to.equal(file.mimetype);
|
||||
const updateData = {
|
||||
_id: '12345',
|
||||
name: 'updated filename',
|
||||
filename: 'updated randomname',
|
||||
path: '/uploads/updated randomname',
|
||||
size: 2048,
|
||||
mimetype: 'image/jpeg'
|
||||
};
|
||||
file.data = updateData;
|
||||
yield file.save();
|
||||
chai_1.expect(file._id).to.equal(insertedFile._id);
|
||||
const updatedFile = yield files.findOne({ _id: file._id });
|
||||
chai_1.expect(updatedFile._id).to.equal(savedFile._id);
|
||||
chai_1.expect(updatedFile.name).to.equal(updateData.name);
|
||||
chai_1.expect(updatedFile.filename).to.equal(updateData.filename);
|
||||
chai_1.expect(updatedFile.path).to.equal(updateData.path);
|
||||
chai_1.expect(updatedFile.size).to.equal(updateData.size);
|
||||
chai_1.expect(updatedFile.mimetype).to.equal(updateData.mimetype);
|
||||
yield file.destroy();
|
||||
chai_1.expect(file._id).to.be.undefined;
|
||||
const removedFile = yield files.findOne({ _id: updatedFile._id });
|
||||
chai_1.expect(removedFile).to.be.null;
|
||||
}));
|
||||
it('Static get method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
name: 'filename',
|
||||
filename: 'randomname',
|
||||
path: '/uploads/randomname',
|
||||
size: 1024,
|
||||
mimetype: 'image/png'
|
||||
};
|
||||
const file = new file_1.default(initialData);
|
||||
const savedFile = yield file.save();
|
||||
if (savedFile._id !== undefined) {
|
||||
const foundFile = yield file_1.default.get(savedFile._id);
|
||||
const { data } = foundFile;
|
||||
chai_1.expect(data._id).to.equal(savedFile._id);
|
||||
chai_1.expect(data.name).to.equal(savedFile.name);
|
||||
chai_1.expect(data.filename).to.equal(savedFile.filename);
|
||||
chai_1.expect(data.path).to.equal(savedFile.path);
|
||||
chai_1.expect(data.size).to.equal(savedFile.size);
|
||||
chai_1.expect(data.mimetype).to.equal(savedFile.mimetype);
|
||||
}
|
||||
yield file.destroy();
|
||||
}));
|
||||
it('Static getByFilename method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
name: 'filename',
|
||||
filename: 'randomname',
|
||||
path: '/uploads/randomname',
|
||||
size: 1024,
|
||||
mimetype: 'image/png'
|
||||
};
|
||||
const file = new file_1.default(initialData);
|
||||
const savedFile = yield file.save();
|
||||
if (savedFile.filename !== undefined) {
|
||||
const foundFile = yield file_1.default.getByFilename(savedFile.filename);
|
||||
const { data } = foundFile;
|
||||
chai_1.expect(data._id).to.equal(savedFile._id);
|
||||
chai_1.expect(data.name).to.equal(savedFile.name);
|
||||
chai_1.expect(data.filename).to.equal(savedFile.filename);
|
||||
chai_1.expect(data.path).to.equal(savedFile.path);
|
||||
chai_1.expect(data.size).to.equal(savedFile.size);
|
||||
chai_1.expect(data.mimetype).to.equal(savedFile.mimetype);
|
||||
}
|
||||
yield file.destroy();
|
||||
}));
|
||||
it('Static getAll method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const filesToSave = [
|
||||
new file_1.default({
|
||||
name: 'filename1',
|
||||
filename: 'randomname1',
|
||||
path: '/uploads/randomname1',
|
||||
size: 1024,
|
||||
mimetype: 'image/png'
|
||||
}),
|
||||
new file_1.default({
|
||||
name: 'filename2',
|
||||
filename: 'randomname2',
|
||||
path: '/uploads/randomname2',
|
||||
size: 2048,
|
||||
mimetype: 'image/jpeg'
|
||||
}),
|
||||
];
|
||||
const savedFiles = yield Promise.all(filesToSave.map(file => file.save()));
|
||||
const foundFiles = yield file_1.default.getAll({ _id: { $in: savedFiles.map(file => file._id) } });
|
||||
chai_1.expect(foundFiles.length).to.equal(2);
|
||||
foundFiles.forEach((file, i) => {
|
||||
chai_1.expect(file.name).to.equal(filesToSave[i].name);
|
||||
chai_1.expect(file.filename).to.equal(filesToSave[i].filename);
|
||||
chai_1.expect(file.path).to.equal(filesToSave[i].path);
|
||||
chai_1.expect(file.size).to.equal(filesToSave[i].size);
|
||||
chai_1.expect(file.mimetype).to.equal(filesToSave[i].mimetype);
|
||||
});
|
||||
}));
|
||||
});
|
|
@ -1,329 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chai_1 = require("chai");
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const page_1 = __importDefault(require("../../src/models/page"));
|
||||
const translation_1 = __importDefault(require("../../src/utils/translation"));
|
||||
const database_1 = __importDefault(require("../../src/utils/database"));
|
||||
const pages = database_1.default['pages'];
|
||||
describe('Page model', () => {
|
||||
const transformToUri = (text) => {
|
||||
return translation_1.default(text
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/[^a-zA-Z0-9А-Яа-яЁё ]/g, ' ')
|
||||
.replace(/ +/g, ' ')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(' ')
|
||||
.join('-'));
|
||||
};
|
||||
after(() => {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './pages.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
it('Working with empty model', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let page = new page_1.default();
|
||||
chai_1.expect(page.data).to.be.a('object');
|
||||
let { data } = page;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.title).to.be.empty;
|
||||
chai_1.expect(data.uri).to.be.empty;
|
||||
chai_1.expect(data.body).to.be.undefined;
|
||||
chai_1.expect(data.parent).to.be.equal('0');
|
||||
page = new page_1.default();
|
||||
data = page.data;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.title).to.be.empty;
|
||||
chai_1.expect(data.uri).to.be.empty;
|
||||
chai_1.expect(data.body).to.be.undefined;
|
||||
chai_1.expect(data.parent).to.be.equal('0');
|
||||
const initialData = {
|
||||
_id: 'page_id',
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
page = new page_1.default(initialData);
|
||||
const json = page.toJSON();
|
||||
data = page.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.title).to.equal(initialData.body.blocks[0].data.text);
|
||||
chai_1.expect(data.uri).to.be.empty;
|
||||
chai_1.expect(data.body).to.deep.equal(initialData.body);
|
||||
chai_1.expect(data.parent).to.be.equal('0');
|
||||
chai_1.expect(json._id).to.equal(initialData._id);
|
||||
chai_1.expect(json.title).to.equal(initialData.body.blocks[0].data.text);
|
||||
chai_1.expect(json.title).to.equal(initialData.body.blocks[0].data.text);
|
||||
chai_1.expect(json.body).to.deep.equal(initialData.body);
|
||||
chai_1.expect(json.parent).to.be.equal('0');
|
||||
const update = {
|
||||
_id: '12345',
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Updated page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
page.data = update;
|
||||
data = page.data;
|
||||
chai_1.expect(data._id).to.equal(initialData._id);
|
||||
chai_1.expect(data.title).to.equal(update.body.blocks[0].data.text);
|
||||
chai_1.expect(data.uri).to.be.empty;
|
||||
chai_1.expect(data.body).to.equal(update.body);
|
||||
chai_1.expect(data.parent).to.be.equal('0');
|
||||
}));
|
||||
it('Saving, updating and deleting model in the database', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'New page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
const page = new page_1.default(initialData);
|
||||
const savedPage = yield page.save();
|
||||
chai_1.expect(savedPage._id).not.be.undefined;
|
||||
chai_1.expect(savedPage.title).to.equal(initialData.body.blocks[0].data.text);
|
||||
chai_1.expect(savedPage.uri).to.equal(transformToUri(initialData.body.blocks[0].data.text));
|
||||
chai_1.expect(savedPage.body).to.equal(initialData.body);
|
||||
chai_1.expect(page._id).not.be.undefined;
|
||||
const insertedPage = yield pages.findOne({ _id: page._id });
|
||||
chai_1.expect(insertedPage._id).to.equal(page._id);
|
||||
chai_1.expect(insertedPage.title).to.equal(page.title);
|
||||
chai_1.expect(insertedPage.uri).to.equal(page.uri);
|
||||
chai_1.expect(insertedPage.body).to.deep.equal(page.body);
|
||||
const updateData = {
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Updated page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
uri: 'updated-uri'
|
||||
};
|
||||
page.data = updateData;
|
||||
yield page.save();
|
||||
chai_1.expect(page._id).to.equal(insertedPage._id);
|
||||
const updatedPage = yield pages.findOne({ _id: page._id });
|
||||
chai_1.expect(updatedPage._id).to.equal(savedPage._id);
|
||||
chai_1.expect(updatedPage.title).to.equal(updateData.body.blocks[0].data.text);
|
||||
chai_1.expect(updatedPage.uri).to.equal(updateData.uri);
|
||||
chai_1.expect(updatedPage.body).to.deep.equal(updateData.body);
|
||||
yield page.destroy();
|
||||
chai_1.expect(page._id).to.be.undefined;
|
||||
const removedPage = yield pages.findOne({ _id: updatedPage._id });
|
||||
chai_1.expect(removedPage).to.be.null;
|
||||
}));
|
||||
it('Handle multiple page creation with the same uri', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'New page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
const firstPage = new page_1.default(initialData);
|
||||
let firstSavedPage = yield firstPage.save();
|
||||
const secondPage = new page_1.default(initialData);
|
||||
const secondSavedPage = yield secondPage.save();
|
||||
chai_1.expect(secondSavedPage.uri).to.equal(transformToUri(initialData.body.blocks[0].data.text) + '-1');
|
||||
const newUri = 'new-uri';
|
||||
firstPage.data = Object.assign(Object.assign({}, firstPage.data), { uri: newUri });
|
||||
firstSavedPage = yield firstPage.save();
|
||||
chai_1.expect(firstSavedPage.uri).to.equal(newUri);
|
||||
const thirdPage = new page_1.default(initialData);
|
||||
const thirdSavedPage = yield thirdPage.save();
|
||||
chai_1.expect(thirdSavedPage.uri).to.equal(transformToUri(initialData.body.blocks[0].data.text));
|
||||
}));
|
||||
it('Static get method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const initialData = {
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Test Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
const page = new page_1.default(initialData);
|
||||
const savedPage = yield page.save();
|
||||
if (savedPage._id !== undefined) {
|
||||
const foundPage = yield page_1.default.get(savedPage._id);
|
||||
const { data } = foundPage;
|
||||
chai_1.expect(data._id).to.equal(savedPage._id);
|
||||
chai_1.expect(data.title).to.equal(initialData.body.blocks[0].data.text);
|
||||
chai_1.expect(data.uri).to.equal(transformToUri(initialData.body.blocks[0].data.text));
|
||||
chai_1.expect(data.body).to.deep.equal(initialData.body);
|
||||
}
|
||||
yield page.destroy();
|
||||
}));
|
||||
it('Static getAll method', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pagesToSave = [
|
||||
new page_1.default({
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page 1 header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}),
|
||||
new page_1.default({
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page 2 header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
];
|
||||
const savedPages = yield Promise.all(pagesToSave.map(page => page.save()));
|
||||
const foundPages = yield page_1.default.getAll({ _id: { $in: savedPages.map(page => page._id) } });
|
||||
chai_1.expect(foundPages.length).to.equal(2);
|
||||
foundPages.forEach((page, i) => {
|
||||
chai_1.expect(page.title).to.equal(pagesToSave[i].body.blocks[0].data.text);
|
||||
chai_1.expect(page.uri).to.equal(transformToUri(pagesToSave[i].body.blocks[0].data.text));
|
||||
chai_1.expect(page.body).to.deep.equal(pagesToSave[i].body);
|
||||
});
|
||||
}));
|
||||
it('Parent pages', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const parent = new page_1.default({
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Parent page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
const { _id: parentId } = yield parent.save();
|
||||
const child = new page_1.default({
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Child page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
parent: parentId,
|
||||
});
|
||||
// child.parent = parent;
|
||||
const { _id: childId } = yield child.save();
|
||||
const testedParent = yield child.getParent();
|
||||
chai_1.expect(testedParent).to.be.not.null;
|
||||
if (testedParent) {
|
||||
chai_1.expect(testedParent._id).to.equal(parentId);
|
||||
chai_1.expect(testedParent.title).to.equal(parent.body.blocks[0].data.text);
|
||||
chai_1.expect(testedParent.uri).to.equal(transformToUri(parent.body.blocks[0].data.text));
|
||||
chai_1.expect(testedParent.body).to.deep.equal(parent.body);
|
||||
}
|
||||
const children = yield parent.children;
|
||||
chai_1.expect(children.length).to.equal(1);
|
||||
const testedChild = children.pop();
|
||||
chai_1.expect(testedChild._id).to.equal(childId);
|
||||
chai_1.expect(testedChild.title).to.equal(child.body.blocks[0].data.text);
|
||||
chai_1.expect(testedChild.uri).to.equal(transformToUri(child.body.blocks[0].data.text));
|
||||
chai_1.expect(testedChild.body).to.deep.equal(child.body);
|
||||
chai_1.expect(testedChild._parent).to.equal(child._parent);
|
||||
chai_1.expect(testedChild._parent).to.equal(parent._id);
|
||||
parent.destroy();
|
||||
child.destroy();
|
||||
}));
|
||||
it('Extracting title from page body', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pageData = {
|
||||
body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
const page = new page_1.default(pageData);
|
||||
chai_1.expect(page.title).to.equal(pageData.body.blocks[0].data.text);
|
||||
}));
|
||||
it('test deletion', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pages = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||||
const orders = {
|
||||
'0': ['1', '2', '3'],
|
||||
'1': ['4', '5'],
|
||||
'5': ['6', '7', '8'],
|
||||
'3': ['9'],
|
||||
};
|
||||
function deleteRecursively(startFrom) {
|
||||
const order = orders[startFrom];
|
||||
if (!order) {
|
||||
const found = pages.indexOf(startFrom);
|
||||
pages.splice(found, 1);
|
||||
return;
|
||||
}
|
||||
order.forEach(id => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
deleteRecursively(id);
|
||||
});
|
||||
const found = pages.indexOf(startFrom);
|
||||
pages.splice(found, 1);
|
||||
}
|
||||
}));
|
||||
});
|
|
@ -1,128 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chai_1 = require("chai");
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const pageOrder_1 = __importDefault(require("../../src/models/pageOrder"));
|
||||
const database_1 = __importDefault(require("../../src/utils/database"));
|
||||
const pagesOrder = database_1.default['pagesOrder'];
|
||||
describe('PageOrder model', () => {
|
||||
after(() => {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './pagesOrder.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
});
|
||||
it('Empty Model', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pageOrder = new pageOrder_1.default();
|
||||
chai_1.expect(pageOrder.data).to.be.a('object');
|
||||
let { data } = pageOrder;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.page).to.be.to.equal('0');
|
||||
chai_1.expect(data.order).to.be.an('array').that.is.empty;
|
||||
let page = new pageOrder_1.default();
|
||||
data = page.data;
|
||||
chai_1.expect(data._id).to.be.undefined;
|
||||
chai_1.expect(data.page).to.be.to.equal('0');
|
||||
chai_1.expect(data.order).to.be.an('array').that.is.empty;
|
||||
const testData = {
|
||||
_id: 'order_id',
|
||||
page: 'page_id',
|
||||
order: []
|
||||
};
|
||||
page = new pageOrder_1.default(testData);
|
||||
data = page.data;
|
||||
chai_1.expect(data._id).to.equal(testData._id);
|
||||
chai_1.expect(data.page).to.equal(testData.page);
|
||||
chai_1.expect(data.order).to.be.an('array').that.is.empty;
|
||||
}));
|
||||
it('Testing Model methods', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const testData = {
|
||||
page: 'page_id',
|
||||
order: ['1', '2']
|
||||
};
|
||||
const pageOrder = new pageOrder_1.default(testData);
|
||||
const { data } = yield pageOrder.save();
|
||||
chai_1.expect(data._id).not.be.undefined;
|
||||
chai_1.expect(data.page).to.equal(testData.page);
|
||||
chai_1.expect(data.order).to.deep.equals(testData.order);
|
||||
const insertedPageOrder = yield pagesOrder.findOne({ _id: data._id });
|
||||
chai_1.expect(insertedPageOrder._id).to.equal(data._id);
|
||||
chai_1.expect(insertedPageOrder.page).to.equal(data.page);
|
||||
chai_1.expect(insertedPageOrder.order).to.deep.equal(data.order);
|
||||
const updateData = {
|
||||
page: 'page_id_2',
|
||||
order: ['3']
|
||||
};
|
||||
pageOrder.data = updateData;
|
||||
yield pageOrder.save();
|
||||
chai_1.expect(pageOrder.data._id).to.equal(insertedPageOrder._id);
|
||||
const updatedData = yield pagesOrder.findOne({ _id: insertedPageOrder._id });
|
||||
chai_1.expect(updatedData.page).to.equal(updateData.page);
|
||||
chai_1.expect(updatedData.order).to.deep.equal(updateData.order);
|
||||
yield pageOrder.destroy();
|
||||
chai_1.expect(pageOrder.data._id).to.be.undefined;
|
||||
const removedPage = yield pagesOrder.findOne({ _id: updatedData._id });
|
||||
chai_1.expect(removedPage).to.be.null;
|
||||
}));
|
||||
it('Testing push and remove order methods', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const testData = {
|
||||
page: 'page_id',
|
||||
order: ['1', '2']
|
||||
};
|
||||
const pageOrder = new pageOrder_1.default(testData);
|
||||
yield pageOrder.save();
|
||||
pageOrder.push('3');
|
||||
chai_1.expect(pageOrder.data.order).to.be.an('array').that.is.not.empty;
|
||||
if (pageOrder.data.order !== undefined) {
|
||||
pageOrder.data.order.forEach((el) => {
|
||||
chai_1.expect(el).to.be.an('string');
|
||||
});
|
||||
}
|
||||
chai_1.expect(pageOrder.data.order).to.deep.equals(['1', '2', '3']);
|
||||
pageOrder.remove('2');
|
||||
chai_1.expect(pageOrder.data.order).to.deep.equals(['1', '3']);
|
||||
// Not allowed by TypeScript
|
||||
// expect(() => {
|
||||
// pageOrder.push(3);
|
||||
// }).to.throw('given id is not string');
|
||||
pageOrder.push('4');
|
||||
pageOrder.push('5');
|
||||
pageOrder.push('2');
|
||||
pageOrder.putAbove('2', '3');
|
||||
chai_1.expect(pageOrder.data.order).to.deep.equals(['1', '2', '3', '4', '5']);
|
||||
pageOrder.putAbove('2', '10');
|
||||
chai_1.expect(pageOrder.data.order).to.deep.equals(['1', '2', '3', '4', '5']);
|
||||
yield pageOrder.destroy();
|
||||
}));
|
||||
it('Testing static methods', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const testData = {
|
||||
page: 'page_id',
|
||||
order: ['1', '2']
|
||||
};
|
||||
const pageOrder = new pageOrder_1.default(testData);
|
||||
const insertedData = yield pageOrder.save();
|
||||
if (insertedData.data.page !== undefined) {
|
||||
const insertedPageOrder = yield pageOrder_1.default.get(insertedData.data.page);
|
||||
chai_1.expect(insertedPageOrder).to.instanceOf(pageOrder_1.default);
|
||||
chai_1.expect(insertedPageOrder.data._id).to.be.equal(insertedData.data._id);
|
||||
}
|
||||
const emptyInstance = yield pageOrder_1.default.get('');
|
||||
chai_1.expect(emptyInstance.data.page).to.be.equal('0');
|
||||
chai_1.expect(emptyInstance.data.order).to.be.an('array').that.is.empty;
|
||||
yield pageOrder.destroy();
|
||||
}));
|
||||
});
|
227
test/rcparser.js
227
test/rcparser.js
|
@ -1,227 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chai_1 = require("chai");
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const rcparser_1 = __importDefault(require("../src/utils/rcparser"));
|
||||
const sinon = require("sinon");
|
||||
const rcPath = path_1.default.resolve(process.cwd(), config_1.default.get('rcFile'));
|
||||
describe('RC file parser test', () => {
|
||||
beforeEach(function () {
|
||||
// spy = sinon.stub(console, 'log');
|
||||
});
|
||||
afterEach(() => {
|
||||
if (fs_1.default.existsSync(rcPath)) {
|
||||
fs_1.default.unlinkSync(rcPath);
|
||||
}
|
||||
});
|
||||
it('Default config', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(parsedConfig).to.be.deep.equal(rcparser_1.default.DEFAULTS);
|
||||
}));
|
||||
it('Invalid JSON formatted config', () => {
|
||||
const invalidJson = '{title: "Codex Docs"}';
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, invalidJson, 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('CodeX Docs rc file should be in JSON format.')).to.be.true;
|
||||
chai_1.expect(parsedConfig).to.be.deep.equal(rcparser_1.default.DEFAULTS);
|
||||
spy.restore();
|
||||
});
|
||||
it('Normal config', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
{ title: 'Option 1', uri: '/option1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(parsedConfig).to.be.deep.equal(normalConfig);
|
||||
});
|
||||
it('Missed title', () => {
|
||||
const normalConfig = {
|
||||
menu: [
|
||||
{ title: 'Option 1', uri: '/option1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(normalConfig.menu);
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(rcparser_1.default.DEFAULTS.title);
|
||||
});
|
||||
it('Missed menu', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation'
|
||||
};
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(rcparser_1.default.DEFAULTS.menu);
|
||||
});
|
||||
it('Menu is not an array', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: {
|
||||
0: { title: 'Option 1', uri: '/option1' },
|
||||
1: { title: 'Option 2', uri: '/option2' },
|
||||
2: { title: 'Option 3', uri: '/option3' }
|
||||
}
|
||||
};
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const spy = sinon.spy(console, 'log');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu section in the rc file must be an array.')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(rcparser_1.default.DEFAULTS.menu);
|
||||
spy.restore();
|
||||
});
|
||||
it('Menu option is a string', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
'Option 1',
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 1', uri: '/option-1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
});
|
||||
it('Menu option is not a string or an object', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
[{ title: 'Option 1', uri: '/option1' }],
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu option #1 in rc file must be a string or an object')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
spy.restore();
|
||||
});
|
||||
it('Menu option title is undefined', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
{ uri: '/option1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu option #1 title must be a string.')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
spy.restore();
|
||||
});
|
||||
it('Menu option title is not a string', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
{ title: [], uri: '/option1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu option #1 title must be a string.')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
spy.restore();
|
||||
});
|
||||
it('Menu option uri is undefined', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
{ title: 'Option 1' },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu option #1 uri must be a string.')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
spy.restore();
|
||||
});
|
||||
it('Menu option title is not a string', () => {
|
||||
const normalConfig = {
|
||||
title: 'Documentation',
|
||||
menu: [
|
||||
{ title: 'Option 1', uri: [] },
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
]
|
||||
};
|
||||
const expectedMenu = [
|
||||
{ title: 'Option 2', uri: '/option2' },
|
||||
{ title: 'Option 3', uri: '/option3' }
|
||||
];
|
||||
const spy = sinon.spy(console, 'log');
|
||||
fs_1.default.writeFileSync(rcPath, JSON.stringify(normalConfig), 'utf8');
|
||||
const parsedConfig = rcparser_1.default.getConfiguration();
|
||||
chai_1.expect(spy.calledOnce).to.be.true;
|
||||
chai_1.expect(spy.calledWith('Menu option #1 uri must be a string.')).to.be.true;
|
||||
chai_1.expect(parsedConfig.title).to.be.equal(normalConfig.title);
|
||||
chai_1.expect(parsedConfig.menu).to.be.deep.equal(expectedMenu);
|
||||
spy.restore();
|
||||
});
|
||||
});
|
|
@ -1,60 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const server_1 = __importDefault(require("../../bin/server"));
|
||||
const app = server_1.default.app;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const chai_1 = __importDefault(require("chai"));
|
||||
const chai_http_1 = __importDefault(require("chai-http"));
|
||||
const { expect } = chai_1.default;
|
||||
chai_1.default.use(chai_http_1.default);
|
||||
describe('Aliases REST: ', () => {
|
||||
let agent;
|
||||
before(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
agent = chai_1.default.request.agent(app);
|
||||
}));
|
||||
after(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './pages.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
const pathToAliasDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './aliases.db');
|
||||
if (fs_1.default.existsSync(pathToAliasDB)) {
|
||||
fs_1.default.unlinkSync(pathToAliasDB);
|
||||
}
|
||||
}));
|
||||
it('Finding page with alias', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
time: 1548375408533,
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Test header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
const put = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body });
|
||||
expect(put).to.have.status(200);
|
||||
expect(put).to.be.json;
|
||||
const { result: { uri } } = put.body;
|
||||
const get = yield agent.get('/' + uri);
|
||||
expect(get).to.have.status(200);
|
||||
}));
|
||||
});
|
|
@ -1,431 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const server_1 = __importDefault(require("../../bin/server"));
|
||||
const app = server_1.default.app;
|
||||
const page_1 = __importDefault(require("../../src/models/page"));
|
||||
const page_2 = __importDefault(require("../../src/models/page"));
|
||||
const pageOrder_1 = __importDefault(require("../../src/models/pageOrder"));
|
||||
const translation_1 = __importDefault(require("../../src/utils/translation"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
const chai_1 = __importDefault(require("chai"));
|
||||
const chai_http_1 = __importDefault(require("chai-http"));
|
||||
const { expect } = chai_1.default;
|
||||
chai_1.default.use(chai_http_1.default);
|
||||
describe('Pages REST: ', () => {
|
||||
let agent;
|
||||
const transformToUri = (text) => {
|
||||
return translation_1.default(text
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/[^a-zA-Z0-9А-Яа-яЁё ]/g, ' ')
|
||||
.replace(/ +/g, ' ')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(' ')
|
||||
.join('-'));
|
||||
};
|
||||
before(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
agent = chai_1.default.request.agent(app);
|
||||
}));
|
||||
after(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pathToPagesDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './pages.db');
|
||||
const pathToPagesOrderDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './pagesOrder.db');
|
||||
const pathToAliasesDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './aliases.db');
|
||||
if (fs_1.default.existsSync(pathToPagesDB)) {
|
||||
fs_1.default.unlinkSync(pathToPagesDB);
|
||||
}
|
||||
if (fs_1.default.existsSync(pathToPagesOrderDB)) {
|
||||
fs_1.default.unlinkSync(pathToPagesOrderDB);
|
||||
}
|
||||
if (fs_1.default.existsSync(pathToAliasesDB)) {
|
||||
fs_1.default.unlinkSync(pathToAliasesDB);
|
||||
}
|
||||
}));
|
||||
it('Creating page', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
const parent = 0;
|
||||
const res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { success, result } = res.body;
|
||||
expect(success).to.be.true;
|
||||
expect(result._id).to.be.a('string');
|
||||
expect(result.title).to.equal(body.blocks[0].data.text);
|
||||
expect(result.uri).to.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(result.body).to.deep.equal(body);
|
||||
const createdPage = yield page_1.default.get(result._id);
|
||||
expect(createdPage).not.be.null;
|
||||
expect(createdPage._id).to.equal(result._id);
|
||||
expect(createdPage.title).to.equal(body.blocks[0].data.text);
|
||||
expect(createdPage.uri).to.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(createdPage.body).to.deep.equal(body);
|
||||
const pageOrder = yield pageOrder_1.default.get('' + (createdPage.data.parent || 0));
|
||||
expect(pageOrder.order).to.be.an('array');
|
||||
yield createdPage.destroy();
|
||||
yield pageOrder.destroy();
|
||||
}));
|
||||
it('Page data validation on create', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ someField: 'Some text' });
|
||||
expect(res).to.have.status(400);
|
||||
expect(res).to.be.json;
|
||||
const { success, error } = res.body;
|
||||
expect(success).to.be.false;
|
||||
expect(error).to.equal('Error: Some of required fields is missed');
|
||||
}));
|
||||
it('Finding page', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
const put = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body });
|
||||
expect(put).to.have.status(200);
|
||||
expect(put).to.be.json;
|
||||
const { result: { _id } } = put.body;
|
||||
const get = yield agent.get(`/api/page/${_id}`);
|
||||
expect(get).to.have.status(200);
|
||||
expect(get).to.be.json;
|
||||
const { success } = get.body;
|
||||
expect(success).to.be.true;
|
||||
const foundPage = yield page_1.default.get(_id);
|
||||
const pageOrder = yield pageOrder_1.default.get('' + foundPage._parent);
|
||||
expect(foundPage._id).to.equal(_id);
|
||||
expect(foundPage.title).to.equal(body.blocks[0].data.text);
|
||||
expect(foundPage.uri).to.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(foundPage.body).to.deep.equal(body);
|
||||
yield pageOrder.destroy();
|
||||
yield foundPage.destroy();
|
||||
}));
|
||||
it('Finding page with not existing id', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const res = yield agent.get('/api/page/not-existing-id');
|
||||
expect(res).to.have.status(400);
|
||||
expect(res).to.be.json;
|
||||
const { success, error } = res.body;
|
||||
expect(success).to.be.false;
|
||||
expect(error).to.equal('Page with given id does not exist');
|
||||
}));
|
||||
it('Updating page', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
let res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { result: { _id } } = res.body;
|
||||
const updatedBody = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Updated page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
const updatedUri = 'updated-uri';
|
||||
res = yield agent
|
||||
.post(`/api/page/${_id}`)
|
||||
.send({ body: updatedBody, uri: updatedUri });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { success, result } = res.body;
|
||||
expect(success).to.be.true;
|
||||
expect(result._id).to.equal(_id);
|
||||
expect(result.title).not.equal(body.blocks[0].data.text);
|
||||
expect(result.title).to.equal(updatedBody.blocks[0].data.text);
|
||||
expect(result.uri).not.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(result.uri).to.equal(updatedUri);
|
||||
expect(result.body).not.equal(body);
|
||||
expect(result.body).to.deep.equal(updatedBody);
|
||||
const updatedPage = yield page_1.default.get(_id);
|
||||
const pageOrder = yield pageOrder_1.default.get('' + updatedPage._parent);
|
||||
expect(updatedPage._id).to.equal(_id);
|
||||
expect(updatedPage.title).not.equal(body.blocks[0].data.text);
|
||||
expect(updatedPage.title).to.equal(updatedBody.blocks[0].data.text);
|
||||
expect(updatedPage.uri).not.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(updatedPage.uri).to.equal(updatedUri);
|
||||
expect(updatedPage.body).not.equal(body);
|
||||
expect(updatedPage.body).to.deep.equal(updatedBody);
|
||||
yield pageOrder.destroy();
|
||||
yield updatedPage.destroy();
|
||||
}));
|
||||
it('Handle multiple page creation with the same uri', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
let res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { result: { _id } } = res.body;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body: body });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { success: secondPageSuccess, result: secondPageResult } = res.body;
|
||||
expect(secondPageSuccess).to.be.true;
|
||||
expect(secondPageResult.title).to.equal(body.blocks[0].data.text);
|
||||
expect(secondPageResult.uri).to.equal(transformToUri(body.blocks[0].data.text) + '-1');
|
||||
expect(secondPageResult.body).to.deep.equal(body);
|
||||
const newFirstPageUri = 'New-uri';
|
||||
res = yield agent
|
||||
.post(`/api/page/${_id}`)
|
||||
.send({ body: body, uri: newFirstPageUri });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body: body });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { success: thirdPageSuccess, result: thirdPageResult } = res.body;
|
||||
expect(thirdPageSuccess).to.be.true;
|
||||
expect(thirdPageResult.title).to.equal(body.blocks[0].data.text);
|
||||
expect(thirdPageResult.uri).to.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(thirdPageResult.body).to.deep.equal(body);
|
||||
}));
|
||||
it('Updating page with not existing id', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const res = yield agent
|
||||
.post('/api/page/not-existing-id')
|
||||
.send({ body: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
} });
|
||||
expect(res).to.have.status(400);
|
||||
expect(res).to.be.json;
|
||||
const { success, error } = res.body;
|
||||
expect(success).to.be.false;
|
||||
expect(error).to.equal('Page with given id does not exist');
|
||||
}));
|
||||
it('Removing page', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header to be deleted'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
let res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body });
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { result: { _id } } = res.body;
|
||||
res = yield agent
|
||||
.delete(`/api/page/${_id}`);
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { success, result } = res.body;
|
||||
expect(success).to.be.true;
|
||||
if (result) {
|
||||
expect(result._id).to.be.undefined;
|
||||
expect(result.title).to.equal(body.blocks[0].data.text);
|
||||
expect(result.uri).to.equal(transformToUri(body.blocks[0].data.text));
|
||||
expect(result.body).to.deep.equal(body);
|
||||
const deletedPage = yield page_1.default.get(_id);
|
||||
expect(deletedPage._id).to.be.undefined;
|
||||
}
|
||||
else {
|
||||
expect(result).to.be.null;
|
||||
}
|
||||
}));
|
||||
it('Removing page with not existing id', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const res = yield agent
|
||||
.delete('/api/page/not-existing-id');
|
||||
expect(res).to.have.status(400);
|
||||
expect(res).to.be.json;
|
||||
const { success, error } = res.body;
|
||||
expect(success).to.be.false;
|
||||
expect(error).to.equal('Page with given id does not exist');
|
||||
}));
|
||||
function createPageTree() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
/**
|
||||
* Creating page tree
|
||||
*
|
||||
* 0
|
||||
* / \
|
||||
* 1 2
|
||||
* / \ \
|
||||
* 3 5 6
|
||||
* / / \
|
||||
* 4 7 8
|
||||
*/
|
||||
const body = {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
data: {
|
||||
text: 'Page header'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
let parent, res, result;
|
||||
/** Page 1 */
|
||||
parent = 0;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page1 = result;
|
||||
/** Page 2 */
|
||||
parent = 0;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page2 = result;
|
||||
/** Page 3 */
|
||||
parent = page1._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page3 = result;
|
||||
/** Page 4 */
|
||||
parent = page3._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page4 = result;
|
||||
/** Page 5 */
|
||||
parent = page1._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page5 = result;
|
||||
/** Page 6 */
|
||||
parent = page2._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page6 = result;
|
||||
/** Page 7 */
|
||||
parent = page6._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page7 = result;
|
||||
/** Page 8 */
|
||||
parent = page6._id;
|
||||
res = yield agent
|
||||
.put('/api/page')
|
||||
.send({ body, parent });
|
||||
result = res.body.result;
|
||||
const page8 = result;
|
||||
return [
|
||||
0,
|
||||
page1._id,
|
||||
page2._id,
|
||||
page3._id,
|
||||
page4._id,
|
||||
page5._id,
|
||||
page6._id,
|
||||
page7._id,
|
||||
page8._id
|
||||
];
|
||||
});
|
||||
}
|
||||
it('Removing a page and its children', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pages = yield createPageTree();
|
||||
/**
|
||||
* Deleting from tree page1
|
||||
* Also pages 3, 5 and 4 must be deleted
|
||||
*/
|
||||
yield agent
|
||||
.delete(`/api/page/${pages[1]}`);
|
||||
const page3 = yield page_2.default.get(pages[3]);
|
||||
expect(page3.data._id).to.be.undefined;
|
||||
const page4 = yield page_2.default.get(pages[4]);
|
||||
expect(page4.data._id).to.be.undefined;
|
||||
const page5 = yield page_2.default.get(pages[5]);
|
||||
expect(page5.data._id).to.be.undefined;
|
||||
/** Okay, pages above is deleted */
|
||||
const page2 = yield page_2.default.get(pages[2]);
|
||||
expect(page2.data._id).not.to.be.undefined;
|
||||
/** First check pages 6, 7 and 8 before deleting */
|
||||
let page6 = yield page_2.default.get(pages[6]);
|
||||
expect(page6.data._id).not.to.be.undefined;
|
||||
let page7 = yield page_2.default.get(pages[7]);
|
||||
expect(page7.data._id).not.to.be.undefined;
|
||||
let page8 = yield page_2.default.get(pages[8]);
|
||||
expect(page8.data._id).not.to.be.undefined;
|
||||
/**
|
||||
* Delete page6
|
||||
* also pages 7 and 8 must be deleted
|
||||
*/
|
||||
yield agent
|
||||
.delete(`/api/page/${pages[6]}`);
|
||||
page6 = yield page_2.default.get(pages[6]);
|
||||
expect(page6.data._id).to.be.undefined;
|
||||
page7 = yield page_2.default.get(pages[7]);
|
||||
expect(page7.data._id).to.be.undefined;
|
||||
page8 = yield page_2.default.get(pages[8]);
|
||||
expect(page8.data._id).to.be.undefined;
|
||||
}));
|
||||
});
|
|
@ -1,222 +0,0 @@
|
|||
"use strict";
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const file_type_1 = __importDefault(require("file-type"));
|
||||
const chai_1 = __importDefault(require("chai"));
|
||||
const chai_http_1 = __importDefault(require("chai-http"));
|
||||
const rimraf_1 = __importDefault(require("rimraf"));
|
||||
const { expect } = chai_1.default;
|
||||
const server_1 = __importDefault(require("../../bin/server"));
|
||||
const app = server_1.default.app;
|
||||
const file_1 = __importDefault(require("../../src/models/file"));
|
||||
const config_1 = __importDefault(require("config"));
|
||||
chai_1.default.use(chai_http_1.default);
|
||||
describe('Transport routes: ', () => {
|
||||
let agent;
|
||||
before(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
agent = chai_1.default.request.agent(app);
|
||||
if (!fs_1.default.existsSync('./' + config_1.default.get('uploads'))) {
|
||||
fs_1.default.mkdirSync('./' + config_1.default.get('uploads'));
|
||||
}
|
||||
}));
|
||||
after(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const pathToDB = path_1.default.resolve(__dirname, '../../', config_1.default.get('database'), './files.db');
|
||||
if (fs_1.default.existsSync(pathToDB)) {
|
||||
fs_1.default.unlinkSync(pathToDB);
|
||||
}
|
||||
if (fs_1.default.existsSync('./' + config_1.default.get('uploads'))) {
|
||||
rimraf_1.default.sync('./' + config_1.default.get('uploads'));
|
||||
}
|
||||
}));
|
||||
it('Uploading an image', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const name = 'test_image.png';
|
||||
const image = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
const res = yield agent
|
||||
.post('/api/transport/image')
|
||||
.attach('image', image, name);
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file._id).to.equal(body._id);
|
||||
expect(file.name).to.equal(name);
|
||||
expect(file.filename).to.equal(body.filename);
|
||||
expect(file.path).to.equal(body.path);
|
||||
const type = yield file_type_1.default.fromBuffer(image);
|
||||
expect(type).to.be.not.undefined;
|
||||
if (type !== undefined) {
|
||||
expect(file.mimetype).to.equal(type.mime);
|
||||
expect(file.size).to.equal(image.byteLength);
|
||||
expect(file.path).to.be.not.undefined;
|
||||
if (file.path !== undefined) {
|
||||
const getRes = yield agent
|
||||
.get(file.path);
|
||||
expect(getRes).to.have.status(200);
|
||||
expect(getRes).to.have.header('content-type', type.mime);
|
||||
}
|
||||
}
|
||||
}));
|
||||
it('Uploading an image with map option', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const name = 'test_image.png';
|
||||
const image = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
const res = yield agent
|
||||
.post('/api/transport/image')
|
||||
.attach('image', image, name)
|
||||
.field('map', JSON.stringify({ _id: '_id', path: 'file:url', size: 'file:size', name: 'file:name' }));
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file.name).to.equal(body.file.name);
|
||||
expect(file.path).to.equal(body.file.url);
|
||||
expect(file.size).to.equal(body.file.size);
|
||||
}));
|
||||
it('Uploading a file', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const name = 'test_file.json';
|
||||
const json = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
const res = yield agent
|
||||
.post('/api/transport/file')
|
||||
.attach('file', json, name);
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file._id).to.equal(body._id);
|
||||
expect(file.name).to.equal(name);
|
||||
expect(file.filename).to.equal(body.filename);
|
||||
expect(file.path).to.equal(body.path);
|
||||
expect(file.size).to.equal(json.byteLength);
|
||||
expect(file.path).to.be.not.undefined;
|
||||
if (file.path !== undefined) {
|
||||
const getRes = yield agent
|
||||
.get(file.path);
|
||||
expect(getRes).to.have.status(200);
|
||||
expect(getRes).to.have.header('content-type', new RegExp(`^${file.mimetype}`));
|
||||
}
|
||||
}));
|
||||
it('Uploading a file with map option', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const name = 'test_file.json';
|
||||
const json = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
const res = yield agent
|
||||
.post('/api/transport/file')
|
||||
.attach('file', json, name)
|
||||
.field('map', JSON.stringify({ _id: '_id', path: 'file:url', size: 'file:size', name: 'file:name' }));
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file.name).to.equal(body.file.name);
|
||||
expect(file.path).to.equal(body.file.url);
|
||||
expect(file.size).to.equal(body.file.size);
|
||||
}));
|
||||
it('Send file URL to fetch', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const url = 'https://codex.so/public/app/img/codex-logo.svg';
|
||||
const res = yield agent
|
||||
.post('/api/transport/fetch')
|
||||
.field('url', url);
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file._id).to.equal(body._id);
|
||||
expect(file.name).to.equal(body.name);
|
||||
expect(file.filename).to.equal(body.filename);
|
||||
expect(file.path).to.equal(body.path);
|
||||
expect(file.size).to.equal(body.size);
|
||||
expect(file.path).to.be.not.undefined;
|
||||
if (file.path !== undefined) {
|
||||
const getRes = yield agent
|
||||
.get(file.path);
|
||||
expect(getRes).to.have.status(200);
|
||||
expect(getRes).to.have.header('content-type', file.mimetype);
|
||||
}
|
||||
}));
|
||||
it('Send an file URL to fetch with map option', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
const url = 'https://codex.so/public/app/img/codex-logo.svg';
|
||||
const res = yield agent
|
||||
.post('/api/transport/fetch')
|
||||
.field('url', url)
|
||||
.field('map', JSON.stringify({ _id: '_id', path: 'file:url', size: 'file:size', name: 'file:name' }));
|
||||
expect(res).to.have.status(200);
|
||||
expect(res).to.be.json;
|
||||
const { body } = res;
|
||||
const file = yield file_1.default.get(body._id);
|
||||
expect(body.success).to.equal(1);
|
||||
expect(file.name).to.equal(body.file.name);
|
||||
expect(file.path).to.equal(body.file.url);
|
||||
expect(file.size).to.equal(body.file.size);
|
||||
}));
|
||||
it('Negative tests for file uploading', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let res = yield agent
|
||||
.post('/api/transport/file')
|
||||
.send();
|
||||
let { body } = res;
|
||||
expect(res).to.have.status(400);
|
||||
expect(body.success).to.equal(0);
|
||||
const name = 'test_file.json';
|
||||
const json = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
res = yield agent
|
||||
.post('/api/transport/file')
|
||||
.attach('file', json, name)
|
||||
.field('map', '{unvalid_json)');
|
||||
body = res.body;
|
||||
expect(res).to.have.status(500);
|
||||
expect(body.success).to.equal(0);
|
||||
}));
|
||||
it('Negative tests for image uploading', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let res = yield agent
|
||||
.post('/api/transport/image')
|
||||
.send();
|
||||
let { body } = res;
|
||||
expect(res).to.have.status(400);
|
||||
expect(body.success).to.equal(0);
|
||||
let name = 'test_file.json';
|
||||
const json = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
res = yield agent
|
||||
.post('/api/transport/image')
|
||||
.attach('image', json, name);
|
||||
expect(res).to.have.status(400);
|
||||
name = 'test_image.png';
|
||||
const image = fs_1.default.readFileSync(path_1.default.resolve(`./test/rest/${name}`));
|
||||
res = yield agent
|
||||
.post('/api/transport/image')
|
||||
.attach('image', image, name)
|
||||
.field('map', '{unvalid_json)');
|
||||
body = res.body;
|
||||
expect(res).to.have.status(500);
|
||||
expect(body.success).to.equal(0);
|
||||
}));
|
||||
it('Negative tests for file fetching', () => __awaiter(void 0, void 0, void 0, function* () {
|
||||
let res = yield agent
|
||||
.post('/api/transport/fetch')
|
||||
.send();
|
||||
let { body } = res;
|
||||
expect(res).to.have.status(400);
|
||||
expect(body.success).to.equal(0);
|
||||
const url = 'https://invalidurl';
|
||||
res = yield agent
|
||||
.post('/api/transport/fetch')
|
||||
.field('url', url);
|
||||
body = res.body;
|
||||
expect(res).to.have.status(500);
|
||||
expect(body.success).to.equal(0);
|
||||
})).timeout(50000);
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue