Best JavaScript code snippet using ng-mocks
back.js
Source:back.js
1import $ from 'dom7';2import { document } from 'ssr-window';3import Utils from '../../utils/utils';4import Device from '../../utils/device';5import History from '../../utils/history';6import redirect from './redirect';7import processRouteQueue from './process-route-queue';8function backward(el, backwardOptions) {9 const router = this;10 const app = router.app;11 const view = router.view;12 const options = Utils.extend({13 animate: router.params.animate,14 pushState: true,15 }, backwardOptions);16 const dynamicNavbar = router.dynamicNavbar;17 const separateNavbar = router.separateNavbar;18 const $newPage = $(el);19 const $oldPage = router.$el.children('.page-current');20 if ($newPage.length) {21 // Remove theme elements22 router.removeThemeElements($newPage);23 }24 let $navbarEl;25 let $newNavbarInner;26 let $oldNavbarInner;27 if (dynamicNavbar) {28 $newNavbarInner = $newPage.children('.navbar').children('.navbar-inner');29 if (separateNavbar) {30 $navbarEl = router.$navbarEl;31 if ($newNavbarInner.length > 0) {32 $newPage.children('.navbar').remove();33 }34 if ($newNavbarInner.length === 0 && $newPage[0] && $newPage[0].f7Page) {35 // Try from pageData36 $newNavbarInner = $newPage[0].f7Page.$navbarEl;37 }38 $oldNavbarInner = $navbarEl.find('.navbar-current');39 } else {40 $oldNavbarInner = $oldPage.children('.navbar').children('.navbar-inner');41 }42 }43 router.allowPageChange = false;44 if ($newPage.length === 0 || $oldPage.length === 0) {45 router.allowPageChange = true;46 return router;47 }48 // Remove theme elements49 router.removeThemeElements($newPage);50 // New Page51 $newPage52 .addClass('page-previous')53 .removeClass('stacked')54 .removeAttr('aria-hidden')55 .trigger('page:unstack')56 .trigger('page:position', { position: 'previous' });57 if (dynamicNavbar && $newNavbarInner.length > 0) {58 $newNavbarInner59 .addClass('navbar-previous')60 .removeClass('stacked')61 .removeAttr('aria-hidden');62 }63 // Remove previous page in case of "forced"64 let backIndex;65 if (options.force) {66 if ($oldPage.prev('.page-previous:not(.stacked)').length > 0 || $oldPage.prev('.page-previous').length === 0) {67 if (router.history.indexOf(options.route.url) >= 0) {68 backIndex = router.history.length - router.history.indexOf(options.route.url) - 1;69 router.history = router.history.slice(0, router.history.indexOf(options.route.url) + 2);70 view.history = router.history;71 } else if (router.history[[router.history.length - 2]]) {72 router.history[router.history.length - 2] = options.route.url;73 } else {74 router.history.unshift(router.url);75 }76 if (backIndex && router.params.stackPages) {77 $oldPage.prevAll('.page-previous').each((index, pageToRemove) => {78 const $pageToRemove = $(pageToRemove);79 let $navbarToRemove;80 if (separateNavbar) {81 // $navbarToRemove = $oldNavbarInner.prevAll('.navbar-previous').eq(index);82 $navbarToRemove = $(app.navbar.getElByPage($pageToRemove));83 }84 if ($pageToRemove[0] !== $newPage[0] && $pageToRemove.index() > $newPage.index()) {85 if (router.initialPages.indexOf($pageToRemove[0]) >= 0) {86 $pageToRemove.addClass('stacked');87 $pageToRemove.trigger('page:stack');88 if (separateNavbar) {89 $navbarToRemove.addClass('stacked');90 }91 } else {92 router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined, options);93 router.removePage($pageToRemove);94 if (separateNavbar && $navbarToRemove.length > 0) {95 router.removeNavbar($navbarToRemove);96 }97 }98 }99 });100 } else {101 const $pageToRemove = $oldPage.prev('.page-previous:not(.stacked)');102 let $navbarToRemove;103 if (separateNavbar) {104 // $navbarToRemove = $oldNavbarInner.prev('.navbar-inner:not(.stacked)');105 $navbarToRemove = $(app.navbar.getElByPage($pageToRemove));106 }107 if (router.params.stackPages && router.initialPages.indexOf($pageToRemove[0]) >= 0) {108 $pageToRemove.addClass('stacked');109 $pageToRemove.trigger('page:stack');110 $navbarToRemove.addClass('stacked');111 } else if ($pageToRemove.length > 0) {112 router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined, options);113 router.removePage($pageToRemove);114 if (separateNavbar && $navbarToRemove.length) {115 router.removeNavbar($navbarToRemove);116 }117 }118 }119 }120 }121 // Insert new page122 const newPageInDom = $newPage.parents(document).length > 0;123 const f7Component = $newPage[0].f7Component;124 function insertPage() {125 if ($newPage.next($oldPage).length === 0) {126 if (!newPageInDom && f7Component) {127 f7Component.$mount((componentEl) => {128 $(componentEl).insertBefore($oldPage);129 });130 } else {131 $newPage.insertBefore($oldPage);132 }133 }134 if (separateNavbar && $newNavbarInner.length) {135 $newNavbarInner.insertBefore($oldNavbarInner);136 if ($oldNavbarInner.length > 0) {137 $newNavbarInner.insertBefore($oldNavbarInner);138 } else {139 if (!router.$navbarEl.parents(document).length) {140 router.$el.prepend(router.$navbarEl);141 }142 $navbarEl.append($newNavbarInner);143 }144 }145 if (!newPageInDom) {146 router.pageCallback('mounted', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);147 }148 }149 if (options.preload) {150 // Insert Page151 insertPage();152 // Tab route153 if (options.route.route.tab) {154 router.tabLoad(options.route.route.tab, Utils.extend({}, options, {155 history: false,156 pushState: false,157 preload: true,158 }));159 }160 // Page init and before init events161 router.pageCallback('init', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);162 if ($newPage.prevAll('.page-previous:not(.stacked)').length > 0) {163 $newPage.prevAll('.page-previous:not(.stacked)').each((index, pageToRemove) => {164 const $pageToRemove = $(pageToRemove);165 let $navbarToRemove;166 if (separateNavbar) {167 // $navbarToRemove = $newNavbarInner.prevAll('.navbar-previous:not(.stacked)').eq(index);168 $navbarToRemove = $(app.navbar.getElByPage($pageToRemove));169 }170 if (router.params.stackPages && router.initialPages.indexOf(pageToRemove) >= 0) {171 $pageToRemove.addClass('stacked');172 $pageToRemove.trigger('page:stack');173 if (separateNavbar) {174 $navbarToRemove.addClass('stacked');175 }176 } else {177 router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined);178 router.removePage($pageToRemove);179 if (separateNavbar && $navbarToRemove.length) {180 router.removeNavbar($navbarToRemove);181 }182 }183 });184 }185 router.allowPageChange = true;186 return router;187 }188 // History State189 if (!(Device.ie || Device.edge || (Device.firefox && !Device.ios))) {190 if (router.params.pushState && options.pushState) {191 if (backIndex) History.go(-backIndex);192 else History.back();193 }194 }195 // Update History196 if (router.history.length === 1) {197 router.history.unshift(router.url);198 }199 router.history.pop();200 router.saveHistory();201 // Current Page & Navbar202 router.currentPageEl = $newPage[0];203 if (dynamicNavbar && $newNavbarInner.length) {204 router.currentNavbarEl = $newNavbarInner[0];205 } else {206 delete router.currentNavbarEl;207 }208 // Current Route209 router.currentRoute = options.route;210 // History State211 if (Device.ie || Device.edge || (Device.firefox && !Device.ios)) {212 if (router.params.pushState && options.pushState) {213 if (backIndex) History.go(-backIndex);214 else History.back();215 }216 }217 // Insert Page218 insertPage();219 // Load Tab220 if (options.route.route.tab) {221 router.tabLoad(options.route.route.tab, Utils.extend({}, options, {222 history: false,223 pushState: false,224 }));225 }226 // Page init and before init events227 router.pageCallback('init', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);228 // Before animation callback229 router.pageCallback('beforeIn', $newPage, $newNavbarInner, 'previous', 'current', options);230 router.pageCallback('beforeOut', $oldPage, $oldNavbarInner, 'current', 'next', options);231 // Animation232 function afterAnimation() {233 // Set classes234 const pageClasses = 'page-previous page-current page-next';235 const navbarClasses = 'navbar-previous navbar-current navbar-next';236 $newPage.removeClass(pageClasses).addClass('page-current').removeAttr('aria-hidden');237 $oldPage.removeClass(pageClasses).addClass('page-next').attr('aria-hidden', 'true');238 if (dynamicNavbar) {239 $newNavbarInner.removeClass(navbarClasses).addClass('navbar-current').removeAttr('aria-hidden');240 $oldNavbarInner.removeClass(navbarClasses).addClass('navbar-next').attr('aria-hidden', 'true');241 }242 // After animation event243 router.pageCallback('afterIn', $newPage, $newNavbarInner, 'previous', 'current', options);244 router.pageCallback('afterOut', $oldPage, $oldNavbarInner, 'current', 'next', options);245 // Remove Old Page246 if (router.params.stackPages && router.initialPages.indexOf($oldPage[0]) >= 0) {247 $oldPage.addClass('stacked');248 $oldPage.trigger('page:stack');249 if (separateNavbar) {250 $oldNavbarInner.addClass('stacked');251 }252 } else {253 router.pageCallback('beforeRemove', $oldPage, $oldNavbarInner, 'next', undefined, options);254 router.removePage($oldPage);255 if (separateNavbar && $oldNavbarInner.length) {256 router.removeNavbar($oldNavbarInner);257 }258 }259 router.allowPageChange = true;260 router.emit('routeChanged', router.currentRoute, router.previousRoute, router);261 // Preload previous page262 const preloadPreviousPage = app.theme === 'ios' ? (router.params.preloadPreviousPage || router.params.iosSwipeBack) : router.params.preloadPreviousPage;263 if (preloadPreviousPage && router.history[router.history.length - 2]) {264 router.back(router.history[router.history.length - 2], { preload: true });265 }266 if (router.params.pushState) {267 History.clearRouterQueue();268 }269 }270 function setPositionClasses() {271 const pageClasses = 'page-previous page-current page-next';272 const navbarClasses = 'navbar-previous navbar-current navbar-next';273 $oldPage.removeClass(pageClasses).addClass('page-current');274 $newPage.removeClass(pageClasses).addClass('page-previous').removeAttr('aria-hidden');275 if (dynamicNavbar) {276 $oldNavbarInner.removeClass(navbarClasses).addClass('navbar-current');277 $newNavbarInner.removeClass(navbarClasses).addClass('navbar-previous').removeAttr('aria-hidden');278 }279 }280 if (options.animate) {281 setPositionClasses();282 router.animate($oldPage, $newPage, $oldNavbarInner, $newNavbarInner, 'backward', () => {283 afterAnimation();284 });285 } else {286 afterAnimation();287 }288 return router;289}290function loadBack(backParams, backOptions, ignorePageChange) {291 const router = this;292 if (!router.allowPageChange && !ignorePageChange) return router;293 const params = backParams;294 const options = backOptions;295 const { url, content, el, pageName, template, templateUrl, component, componentUrl } = params;296 if (297 options.route.url298 && router.url === options.route.url299 && !(options.reloadCurrent || options.reloadPrevious)300 && !router.params.allowDuplicateUrls301 ) {302 return false;303 }304 if (!options.route && url) {305 options.route = router.parseRouteUrl(url);306 }307 // Component Callbacks308 function resolve(pageEl, newOptions) {309 return router.backward(pageEl, Utils.extend(options, newOptions));310 }311 function reject() {312 router.allowPageChange = true;313 return router;314 }315 if (url || templateUrl || componentUrl) {316 router.allowPageChange = false;317 }318 // Proceed319 if (content) {320 router.backward(router.getPageEl(content), options);321 } else if (template || templateUrl) {322 // Parse template and send page element323 try {324 router.pageTemplateLoader(template, templateUrl, options, resolve, reject);325 } catch (err) {326 router.allowPageChange = true;327 throw err;328 }329 } else if (el) {330 // Load page from specified HTMLElement or by page name in pages container331 router.backward(router.getPageEl(el), options);332 } else if (pageName) {333 // Load page by page name in pages container334 router.backward(router.$el.children(`.page[data-name="${pageName}"]`).eq(0), options);335 } else if (component || componentUrl) {336 // Load from component (F7/Vue/React/...)337 try {338 router.pageComponentLoader(router.el, component, componentUrl, options, resolve, reject);339 } catch (err) {340 router.allowPageChange = true;341 throw err;342 }343 } else if (url) {344 // Load using XHR345 if (router.xhr) {346 router.xhr.abort();347 router.xhr = false;348 }349 router.xhrRequest(url, options)350 .then((pageContent) => {351 router.backward(router.getPageEl(pageContent), options);352 })353 .catch(() => {354 router.allowPageChange = true;355 });356 }357 return router;358}359function back(...args) {360 const router = this;361 if (router.swipeBackActive) return router;362 let navigateUrl;363 let navigateOptions;364 let route;365 if (typeof args[0] === 'object') {366 navigateOptions = args[0] || {};367 } else {368 navigateUrl = args[0];369 navigateOptions = args[1] || {};370 }371 const { name, params, query } = navigateOptions;372 if (name) {373 // find route by name374 route = router.findRouteByKey('name', name);375 if (!route) {376 throw new Error(`Framework7: route with name "${name}" not found`);377 }378 navigateUrl = router.constructRouteUrl(route, { params, query });379 if (navigateUrl) {380 return router.back(navigateUrl, Utils.extend({}, navigateOptions, {381 name: null,382 params: null,383 query: null,384 }));385 }386 throw new Error(`Framework7: can't construct URL for route with name "${name}"`);387 }388 const app = router.app;389 if (!router.view) {390 app.views.main.router.back(...args);391 return router;392 }393 let currentRouteIsModal = router.currentRoute.modal;394 let modalType;395 if (!currentRouteIsModal) {396 ('popup popover sheet loginScreen actions customModal panel').split(' ').forEach((modalLoadProp) => {397 if (router.currentRoute.route[modalLoadProp]) {398 currentRouteIsModal = true;399 modalType = modalLoadProp;400 }401 });402 }403 if (currentRouteIsModal) {404 const modalToClose = router.currentRoute.modal405 || router.currentRoute.route.modalInstance406 || app[modalType].get();407 const previousUrl = router.history[router.history.length - 2];408 let previousRoute;409 // check if previous route is modal too410 if (modalToClose && modalToClose.$el) {411 const prevOpenedModals = modalToClose.$el.prevAll('.modal-in');412 if (prevOpenedModals.length && prevOpenedModals[0].f7Modal) {413 previousRoute = prevOpenedModals[0].f7Modal.route;414 }415 }416 if (!previousRoute) {417 previousRoute = router.findMatchingRoute(previousUrl);418 }419 if (!previousRoute && previousUrl) {420 previousRoute = {421 url: previousUrl,422 path: previousUrl.split('?')[0],423 query: Utils.parseUrlQuery(previousUrl),424 route: {425 path: previousUrl.split('?')[0],426 url: previousUrl,427 },428 };429 }430 if (!previousRoute || !modalToClose) {431 return router;432 }433 if (router.params.pushState && navigateOptions.pushState !== false) {434 History.back();435 }436 router.currentRoute = previousRoute;437 router.history.pop();438 router.saveHistory();439 router.modalRemove(modalToClose);440 return router;441 }442 const $previousPage = router.$el.children('.page-current').prevAll('.page-previous').eq(0);443 if (!navigateOptions.force && $previousPage.length > 0) {444 if (router.params.pushState445 && $previousPage[0].f7Page446 && router.history[router.history.length - 2] !== $previousPage[0].f7Page.route.url447 ) {448 router.back(449 router.history[router.history.length - 2],450 Utils.extend(navigateOptions, { force: true })451 );452 return router;453 }454 const previousPageRoute = $previousPage[0].f7Page.route;455 processRouteQueue.call(456 router,457 previousPageRoute,458 router.currentRoute,459 () => {460 router.loadBack({ el: $previousPage }, Utils.extend(navigateOptions, {461 route: previousPageRoute,462 }));463 },464 () => {}465 );466 return router;467 }468 // Navigate URL469 if (navigateUrl === '#') {470 navigateUrl = undefined;471 }472 if (navigateUrl && navigateUrl[0] !== '/' && navigateUrl.indexOf('#') !== 0) {473 navigateUrl = ((router.path || '/') + navigateUrl).replace('//', '/');474 }475 if (!navigateUrl && router.history.length > 1) {476 navigateUrl = router.history[router.history.length - 2];477 }478 // Find route to load479 route = router.findMatchingRoute(navigateUrl);480 if (!route) {481 if (navigateUrl) {482 route = {483 url: navigateUrl,484 path: navigateUrl.split('?')[0],485 query: Utils.parseUrlQuery(navigateUrl),486 route: {487 path: navigateUrl.split('?')[0],488 url: navigateUrl,489 },490 };491 }492 }493 if (!route) {494 return router;495 }496 if (route.route.redirect) {497 return redirect.call(router, 'back', route, navigateOptions);498 }499 const options = {};500 if (route.route.options) {501 Utils.extend(options, route.route.options, navigateOptions, { route });502 } else {503 Utils.extend(options, navigateOptions, { route });504 }505 if (options && options.context) {506 route.context = options.context;507 options.route.context = options.context;508 }509 let backForceLoaded;510 if (options.force && router.params.stackPages) {511 router.$el.children('.page-previous.stacked').each((index, pageEl) => {512 if (pageEl.f7Page && pageEl.f7Page.route && pageEl.f7Page.route.url === route.url) {513 backForceLoaded = true;514 router.loadBack({ el: pageEl }, options);515 }516 });517 if (backForceLoaded) {518 return router;519 }520 }521 function resolve() {522 let routerLoaded = false;523 ('url content component pageName el componentUrl template templateUrl').split(' ').forEach((pageLoadProp) => {524 if (route.route[pageLoadProp] && !routerLoaded) {525 routerLoaded = true;526 router.loadBack({ [pageLoadProp]: route.route[pageLoadProp] }, options);527 }528 });529 if (routerLoaded) return;530 // Async531 function asyncResolve(resolveParams, resolveOptions) {532 router.allowPageChange = false;533 if (resolveOptions && resolveOptions.context) {534 if (!route.context) route.context = resolveOptions.context;535 else route.context = Utils.extend({}, route.context, resolveOptions.context);536 options.route.context = route.context;537 }538 router.loadBack(resolveParams, Utils.extend(options, resolveOptions), true);539 }540 function asyncReject() {541 router.allowPageChange = true;542 }543 if (route.route.async) {544 router.allowPageChange = false;545 route.route.async.call(router, route, router.currentRoute, asyncResolve, asyncReject);546 }547 }548 function reject() {549 router.allowPageChange = true;550 }551 if (options.preload) {552 resolve();553 } else {554 processRouteQueue.call(555 router,556 route,557 router.currentRoute,558 () => {559 if (route.route.modules) {560 app561 .loadModules(Array.isArray(route.route.modules) ? route.route.modules : [route.route.modules])562 .then(() => {563 resolve();564 })565 .catch(() => {566 reject();567 });568 } else {569 resolve();570 }571 },572 () => {573 reject();574 },575 );576 }577 // Return Router578 return router;579}...
app.js
Source:app.js
1var createError = require("http-errors");2var express = require("express");3var session = require("express-session");4var path = require("path");5var cookieParser = require("cookie-parser");6var logger = require("morgan");7//We are including mongoose in the program using require8/* const mongoose = require("mongoose"); */9var indexRouter = require("./routes/index");10var todosRouter = require("./routes/todos");11/* var usersRouter = require("./routes/users"); */12/*var usersRouter = require("./routes/usertable");13var productsRouter = require("./routes/products");14var todosRouter = require("./routes/todos");15var forumsRouter = require("./routes/forums");16var hobbiesRouter = require("./routes/hobbies");17var twitterRouter = require("./routes/twitter");18var forumRouter = require("./routes/forum");19var authorRouter = require("./routes/author");20var bookRouter = require("./routes/book");21var categoryRouter = require("./routes/category");22var productRouter = require("./routes/product");23var userRouter = require("./routes/user");24var usernameRouter = require("./routes/username");25var mysqlRouter = require("./routes/mysql");26var todomysqlRouter = require("./routes/todomysql");27var authormysqlRouter = require("./routes/authormysql");28var usermysqlRouter = require("./routes/usermysql");29var cookieRouter = require("./routes/cookie");30var citycookieRouter = require("./routes/citycookie");31var detailcookieRouter = require("./routes/detailcookie");32var dishesRouter = require("./routes/dishes");33var carRouter = require("./routes/car");34var sessionRouter = require("./routes/session");35var usertableRouter = require("./routes/usertable");36var userdetailsRouter = require("./routes/userdetails");37var fileRouter = require("./routes/file");38var createfileRouter = require("./routes/createfile");39var createfolderRouter = require("./routes/createfolder");40var foldercontentsRouter = require("./routes/foldercontents");41var modifyfileRouter = require("./routes/modifyfile");42var uploadsRouter = require("./routes/uploads");43var userregistrationRouter = require("./routes/userregistration");44var usertablemysqlRouter = require("./routes/usertablemysql"); */45/* var usersmysqlRouter = require("./routes/usersmysql");46var loginsessionRouter = require("./routes/loginsession"); */47/* var sqproductsRouter = require("./routes/sqproducts");*/48var app = express();49app.use(50 session({51 secret: "session_secret_key",52 resave: true,53 saveUnintialized: true,54 cookie: {55 secure: false,56 },57 })58);59/* //This line will make all variables written in .env file into our application through process variable60require("dotenv").config();61//We are defining a connection string to connect to the mongodb62console.log(`The application name is ${process.env.appName}`);63//We are defining a connection string to connect to the mongodb64/* let mongoConnUrl = "mongodb://localhost/westsidenode"; 65//We are connecting the mongodb66mongoose.connect(process.env.mongoConnUrl, { useNewUrlParser: true });67//We are getting the connection pointer68let db = mongoose.connection;69//We are now adding error event and it will run if there is any error in connecting to mongodb70db.on("error", function (error) {71 console.log("unable to connect");72 console.log(error);73});74//We are adding open event and responding in the call back function if connection is successful75db.on("open", function () {76 console.log("we are connected to the mongodb server via mongoose");77}); */78// view engine setup79app.set("views", path.join(__dirname, "views"));80app.set("view engine", "pug");81app.use(logger("dev"));82app.use(express.json());83app.use(express.urlencoded({ extended: false }));84app.use(cookieParser());85app.use(express.static(path.join(__dirname, "public")));86app.use("/", indexRouter);87app.use("/todos", todosRouter);88/* app.use("/users", usersRouter); */89/*app.use("/products", productsRouter);90app.use("/todos", todosRouter);91app.use("/forums", forumsRouter);92app.use("/hobbies", hobbiesRouter);93app.use("/twitter", twitterRouter);94app.use("/forum", forumRouter);95app.use("/author", authorRouter);96app.use("/book", bookRouter);97app.use("/category", categoryRouter);98app.use("/product", productRouter);99app.use("/user", userRouter);100app.use("/username", usernameRouter);101app.use("/mysql", mysqlRouter);102app.use("/todomysql", todomysqlRouter);103app.use("/authormysql", authormysqlRouter);104app.use("/usermysql", usermysqlRouter);105app.use("/cookie", cookieRouter);106app.use("/citycookie", citycookieRouter);107app.use("/detailcookie", detailcookieRouter);108app.use("/dishes", dishesRouter);109app.use("/car", carRouter);110app.use("/session", sessionRouter);111app.use("/usertable", usertableRouter);112app.use("/userdetails", userdetailsRouter);113app.use("/file", fileRouter);114app.use("/createfile", createfileRouter);115app.use("/createfolder", createfolderRouter);116app.use("/foldercontents", foldercontentsRouter);117app.use("/modifyfile", modifyfileRouter);118app.use("/uploads", uploadsRouter);119app.use("/userregistration", userregistrationRouter);120app.use("/usertablemysql", usertablemysqlRouter); 121app.use("/usersmysql", usersmysqlRouter);122app.use("/loginsession", loginsessionRouter);*/123/* app.use("/sqproducts", sqproductsRouter); */124// catch 404 and forward to error handler125app.use(function (req, res, next) {126 next(createError(404));127});128// error handler129app.use(function (err, req, res, next) {130 // set locals, only providing error in development131 res.locals.message = err.message;132 res.locals.error = req.app.get("env") === "development" ? err : {};133 // render the error page134 res.status(err.status || 500);135 res.render("error");136});...
admin.js
Source:admin.js
1'use strict';2var express = require('express');3function apiRoutes(router, middleware, controllers) {4 router.get('/users/csv', middleware.authenticate, controllers.admin.users.getCSV);5 var multipart = require('connect-multiparty');6 var multipartMiddleware = multipart();7 var middlewares = [multipartMiddleware, middleware.validateFiles, middleware.applyCSRF, middleware.authenticate];8 router.post('/category/uploadpicture', middlewares, controllers.admin.uploads.uploadCategoryPicture);9 router.post('/uploadfavicon', middlewares, controllers.admin.uploads.uploadFavicon);10 router.post('/uploadTouchIcon', middlewares, controllers.admin.uploads.uploadTouchIcon);11 router.post('/uploadlogo', middlewares, controllers.admin.uploads.uploadLogo);12 router.post('/uploadOgImage', middlewares, controllers.admin.uploads.uploadOgImage);13 router.post('/upload/sound', middlewares, controllers.admin.uploads.uploadSound);14 router.post('/upload/file', middlewares, controllers.admin.uploads.uploadFile);15 router.post('/uploadDefaultAvatar', middlewares, controllers.admin.uploads.uploadDefaultAvatar);16}17function adminRouter(middleware, controllers) {18 var router = express.Router();19 router.use(middleware.admin.buildHeader);20 addRoutes(router, middleware, controllers);21 return router;22}23function apiRouter(middleware, controllers) {24 var router = express.Router();25 addRoutes(router, middleware, controllers);26 apiRoutes(router, middleware, controllers);27 return router;28}29function addRoutes(router, middleware, controllers) {30 var middlewares = [middleware.pluginHooks];31 router.get('/', middlewares, controllers.admin.dashboard.get);32 router.get('/general/dashboard', middlewares, controllers.admin.dashboard.get);33 router.get('/general/languages', middlewares, controllers.admin.languages.get);34 router.get('/general/sounds', middlewares, controllers.admin.sounds.get);35 router.get('/general/navigation', middlewares, controllers.admin.navigation.get);36 router.get('/general/homepage', middlewares, controllers.admin.homepage.get);37 router.get('/general/social', middlewares, controllers.admin.social.get);38 router.get('/manage/categories', middlewares, controllers.admin.categories.getAll);39 router.get('/manage/categories/:category_id', middlewares, controllers.admin.categories.get);40 router.get('/manage/categories/:category_id/analytics', middlewares, controllers.admin.categories.getAnalytics);41 router.get('/manage/privileges/:cid?', middlewares, controllers.admin.privileges.get);42 router.get('/manage/tags', middlewares, controllers.admin.tags.get);43 router.get('/manage/post-queue', middlewares, controllers.admin.postQueue.get);44 router.get('/manage/ip-blacklist', middlewares, controllers.admin.blacklist.get);45 router.get('/manage/users', middlewares, controllers.admin.users.sortByJoinDate);46 router.get('/manage/users/search', middlewares, controllers.admin.users.search);47 router.get('/manage/users/latest', middlewares, controllers.admin.users.sortByJoinDate);48 router.get('/manage/users/not-validated', middlewares, controllers.admin.users.notValidated);49 router.get('/manage/users/no-posts', middlewares, controllers.admin.users.noPosts);50 router.get('/manage/users/top-posters', middlewares, controllers.admin.users.topPosters);51 router.get('/manage/users/most-reputation', middlewares, controllers.admin.users.mostReputaion);52 router.get('/manage/users/inactive', middlewares, controllers.admin.users.inactive);53 router.get('/manage/users/flagged', middlewares, controllers.admin.users.flagged);54 router.get('/manage/users/banned', middlewares, controllers.admin.users.banned);55 router.get('/manage/registration', middlewares, controllers.admin.users.registrationQueue);56 router.get('/manage/admins-mods', middlewares, controllers.admin.adminsMods.get);57 router.get('/manage/groups', middlewares, controllers.admin.groups.list);58 router.get('/manage/groups/:name', middlewares, controllers.admin.groups.get);59 router.get('/manage/uploads', middlewares, controllers.admin.uploads.get);60 router.get('/settings/:term?', middlewares, controllers.admin.settings.get);61 router.get('/appearance/:term?', middlewares, controllers.admin.appearance.get);62 router.get('/extend/plugins', middlewares, controllers.admin.plugins.get);63 router.get('/extend/widgets', middlewares, controllers.admin.extend.widgets.get);64 router.get('/extend/rewards', middlewares, controllers.admin.extend.rewards.get);65 router.get('/advanced/database', middlewares, controllers.admin.database.get);66 router.get('/advanced/events', middlewares, controllers.admin.events.get);67 router.get('/advanced/logs', middlewares, controllers.admin.logs.get);68 router.get('/advanced/errors', middlewares, controllers.admin.errors.get);69 router.get('/advanced/errors/export', middlewares, controllers.admin.errors.export);70 router.get('/advanced/cache', middlewares, controllers.admin.cache.get);71 router.get('/development/logger', middlewares, controllers.admin.logger.get);72 router.get('/development/info', middlewares, controllers.admin.info.get);73}74module.exports = function (app, middleware, controllers) {75 app.use('/admin/', adminRouter(middleware, controllers));76 app.use('/api/admin/', apiRouter(middleware, controllers));...
routes.ts
Source:routes.ts
1import express from "express";2import orderHistoryRouterV1 from "./routes/v1/orderHistory.route"3import masterExportRouterV1 from "./routes/v1/master.export.route";4import exportsRouterV1 from "./routes/v1/exports.route";5import textControlRouterV1 from "./routes/v1/textControl.route";6import masterIssueRouterV1 from "./routes/v1/master.issue.route";7import consentHistoryRouterV1 from "./routes/v1/consentHistory.route";8import customerServiceRouterV1 from "./routes/v1/customerService.route";9import statusRouterV1 from "./routes/v1/status.route";10import newsRouterV1 from "./routes/v1/news.route";11import masterBanksRouterV1 from "./routes/v1/master.bank.route";12import customerStocksRouterV1 from "./routes/v1/customerStocks.route";13import rendersRouterV1 from "./routes/v1/renders.route";14import masterBrokersRouterV1 from "./routes/v1/master.brokers.route";15import customersRouterV1 from "./routes/v1/master.customers.route";16import ordersRouterV1 from "./routes/v1/orders.route";17import usersRouterV1 from "./routes/v1/users.route";18import authRouterV1 from "./routes/v1/auth.route";19import uploadsRouterV1 from "./routes/v1/uploads.route";20// Router imports21// End of router imports22const router = express.Router();23// Route routers24// End of routing routers25router.use("/v1/uploads", uploadsRouterV1);26router.use("/v1/auth", authRouterV1);27router.use("/v1/users", usersRouterV1);28router.use("/v1/orders", ordersRouterV1);29router.use("/v1/masterCustomers", customersRouterV1);30router.use("/v1/masterBrokers", masterBrokersRouterV1);31router.use("/v1/renders", rendersRouterV1);32router.use("/v1/customerStocks", customerStocksRouterV1);33router.use("/v1/masterBanks", masterBanksRouterV1);34router.use("/v1/news", newsRouterV1);35router.use("/v1/status", statusRouterV1);36router.use("/v1/customerService", customerServiceRouterV1);37router.use("/v1/consentHistory", consentHistoryRouterV1);38router.use("/v1/masterIssue", masterIssueRouterV1);39router.use("/v1/textControl", textControlRouterV1);40router.use("/v1/exports", exportsRouterV1);41router.use("/v1/masterExport", masterExportRouterV1);42router.use("/v1/orderHistory", orderHistoryRouterV1);...
api.router.js
Source:api.router.js
1const express = require("express");2const { authenticateRequests } = require("../utils/authenticate-requests");3// IMPORT OF ROUTER TO ALL RESOURCES4const endpointRouter = require("./endpoint/endpoint.router");5const apisTreeRouter = require("./apisTree/apisTree.router");6const schemaRouter = require("./schema/schema.router");7const readmeRouter = require("./readme/readme.router");8const serviceRouter = require("./service/service.router");9const authRouter = require("./auth/auth.router");10const userRouter = require("./user/user.router");11const environmentRouter = require("./environment/environment.router");12const devRouter = require("./dev/dev.router");13const apiRouter = express.Router();14// ROUTER TO ALL RESOURCES15apiRouter.use("/endpoint", authenticateRequests, endpointRouter);16apiRouter.use("/apisTree", authenticateRequests, apisTreeRouter);17apiRouter.use("/schema", authenticateRequests, schemaRouter);18apiRouter.use("/readme", authenticateRequests, readmeRouter);19apiRouter.use("/service", authenticateRequests, serviceRouter);20apiRouter.use("/auth", authRouter);21apiRouter.use("/user", authenticateRequests, userRouter);22apiRouter.use("/environment", authenticateRequests, environmentRouter);23apiRouter.use("/dev", devRouter);...
index.ts
Source:index.ts
...21 this._router.use("/shared", sharedRouter.router);22 this._router.use("/import", importRouter.router);23 this._router.use("/session", sessionRouter.router);24 }25 get router(): Router {26 return this._router;27 }...
index.js
Source:index.js
1const express = require('express')2const router = express.Router()3const authRouter = require('./auth.router')4// const accountRouter = require('./account.router');5const userRouter = require('./user.router')6// const cashbackRouter = require('./cashback.router');7// const bonusRouter = require('./bonus.router');8// const payoutRouter = require('./payout.router');9// const staticRouter = require('./static.router');10const partnerRouter = require('./partner.router')11// const rafRouter = require('./raf.router');12const apiRouter = require('./api.router')13const activeUserRouter = require('./active-user-router')14const cashbackRouter = require('./cashback-router')15// routes16router.use('/auth', authRouter)17// router.use('/account', accountRouter);18router.use('/user', userRouter)19// router.use('/cashback', cashbackRouter);20// router.use('/payout', payoutRouter);21// router.use('/static', staticRouter);22// router.use('/bonuses', bonusRouter);23router.use('/partner', partnerRouter)24router.use('/active-user', activeUserRouter)25router.use('/api', apiRouter)26router.use('/cashback', cashbackRouter)...
Using AI Code Generation
1import {RouterTestingModule} from '@angular/router/testing';2describe('AppComponent', () => {3 beforeEach(async(() => {4 TestBed.configureTestingModule({5 imports: [6 }).compileComponents();7 }));8 it('should create the app', async(() => {9 const fixture = TestBed.createComponent(AppComponent);10 const app = fixture.debugElement.componentInstance;11 expect(app).toBeTruthy();12 }));13 it(`should have as title 'app'`, async(() => {14 const fixture = TestBed.createComponent(AppComponent);15 const app = fixture.debugElement.componentInstance;16 expect(app.title).toEqual('app');17 }));18 it('should render title in a h1 tag', async(() => {19 const fixture = TestBed.createComponent(AppComponent);20 fixture.detectChanges();21 const compiled = fixture.debugElement.nativeElement;22 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');23 }));24});25import { Component, OnInit } from '@angular/core';26import { Router } from '@angular/router';27@Component({28})29export class AppComponent implements OnInit {30 title = 'app';31 constructor(private router: Router) { }32 ngOnInit() {33 this.router.navigate(['home']);34 }35}36 Welcome to {{title}}!37 <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMX
Using AI Code Generation
1import { RouterTestingModule } from '@angular/router/testing';2describe('TestComponent', () => {3 let component: TestComponent;4 let fixture: ComponentFixture<TestComponent>;5 beforeEach(async(() => {6 TestBed.configureTestingModule({7 imports: [RouterTestingModule]8 })9 .compileComponents();10 }));11 beforeEach(() => {12 fixture = TestBed.createComponent(TestComponent);13 component = fixture.componentInstance;14 fixture.detectChanges();15 });16 it('should create', () => {17 expect(component).toBeTruthy();18 });19 it('should navigate to /test', () => {20 const router = TestBed.get(Router);21 const spy = spyOn(router, 'navigate');22 component.navigate();23 expect(spy).toHaveBeenCalledWith(['/test']);24 });25});26import { Component } from '@angular/core';27import { Router } from '@angular/router';28@Component({29})30export class TestComponent {31 constructor(private router: Router) { }32 navigate() {33 this.router.navigate(['/test']);34 }35}36import { BrowserModule } from '@angular/platform-browser';37import { NgModule } from '@angular/core';38import { AppRoutingModule } from './app-routing.module';39import { AppComponent } from './app.component';40import { TestComponent } from './test/test.component';41import { RouterModule } from '@angular/router';42@NgModule({43 imports: [44 RouterModule.forRoot([45 { path: 'test', component: TestComponent }46})47export class AppModule { }48import { NgModule } from '@angular/core';49import { Routes, RouterModule } from '@angular/router';50const routes: Routes = [];51@NgModule({52 imports: [RouterModule.forRoot(routes)],53})54export class AppRoutingModule { }55import { async, ComponentFixture, TestBed } from '@angular/core/testing';56import { RouterTestingModule } from '@angular/router/testing';57import { Router } from '@angular/router';58import { TestComponent } from './test.component';59describe('TestComponent
Using AI Code Generation
1import { RouterTestingModule } from '@angular/router/testing';2import { Router } from '@angular/router';3describe('AppComponent', () => {4 let router: Router;5 beforeEach(async(() => {6 TestBed.configureTestingModule({7 imports: [8 RouterTestingModule.withRoutes([])9 }).compileComponents();10 router = TestBed.get(Router);11 }));12 it('should create the app', async(() => {13 const fixture = TestBed.createComponent(AppComponent);14 const app = fixture.debugElement.componentInstance;15 expect(app).toBeTruthy();16 }));17 it(`should have as title 'app'`, async(() => {18 const fixture = TestBed.createComponent(AppComponent);19 const app = fixture.debugElement.componentInstance;20 expect(app.title).toEqual('app');21 }));22 it('should render title in a h1 tag', async(() => {23 const fixture = TestBed.createComponent(AppComponent);24 fixture.detectChanges();25 const compiled = fixture.debugElement.nativeElement;26 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');27 }));28 it('should navigate to a new route', async(() => {29 router.navigate(['']);30 expect(router.url).toEqual('/');31 }));32});33import { Component } from '@angular/core';34@Component({35})36export class AppComponent {37 title = 'app';38}39 Welcome to {{title}}!40import { BrowserModule } from '@angular/platform-browser';41import { NgModule } from '@angular/core';42import { RouterModule } from '@angular/router';43import { AppComponent } from './app.component';44import { HomeComponent } from './home/home.component';45@NgModule({46 imports: [47 RouterModule.forRoot([48 { path: 'home', component: HomeComponent }49})50export class AppModule { }51import { Component, OnInit } from '@angular/core';52@Component({53})54export class HomeComponent implements OnInit {
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { RouterTestingModule } from '@angular/router/testing';3import { AppComponent } from './app.component';4beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));5it('should render the app', () => {6 const fixture = MockRender(AppComponent);7 expect(ngMocks.formatText(fixture)).toContain(8 );9});10import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';11import { RouterTestingModule } from '@angular/router/testing';12import { AppComponent } from './app.component';13beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));14it('should render the app', () => {15 const fixture = MockRender(AppComponent);16 const router = ngMocks.findInstance(Router);17 expect(router).toBeTruthy();18 expect(ngMocks.formatText(fixture)).toContain(19 );20});21import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';22import { RouterTestingModule } from '@angular/router/testing';23import { AppComponent } from './app.component';24beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));25it('should render the app', () => {26 const fixture = MockRender(AppComponent);27 const router = ngMocks.findInstance(Router);28 expect(router).toBeTruthy();29 expect(ngMocks.formatText(fixture)).toContain(30 );31});32import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';33import { RouterTestingModule } from '@angular/router/testing';34import { AppComponent } from './app.component';35beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));36it('should render the app', () => {37 const fixture = MockRender(AppComponent);38 const router = ngMocks.findInstance(Router);39 expect(router).toBeTruthy();40 expect(ngMocks.formatText(fixture)).toContain(41 );42});43import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';44import { RouterTestingModule } from '@angular/router/testing';45import { AppComponent } from './app.component';46beforeEach(() => MockBuilder(AppComponent, RouterTestingModule
Using AI Code Generation
1import { RouterTestingModule } from '@angular/router/testing';2import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, RouterTestingModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.debugElement.componentInstance;9 expect(app).toBeTruthy();10 });11 it(`should have as title 'app'`, () => {12 const fixture = MockRender(AppComponent);13 const app = fixture.debugElement.componentInstance;14 expect(app.title).toEqual('app');15 });16 it('should render title in a h1 tag', () => {17 const fixture = MockRender(AppComponent);18 fixture.detectChanges();19 const compiled = fixture.debugElement.nativeElement;20 expect(compiled.querySelector('h1').textContent).toContain(21 );22 });23 it('should contain router-outlet', () => {24 const fixture = MockRender(AppComponent);25 fixture.detectChanges();26 const compiled = fixture.debugElement.nativeElement;27 expect(compiled.querySelector('router-outlet')).toBeTruthy();28 });29 it('should call router.navigate when clicked', () => {30 const fixture = MockRender(AppComponent);31 fixture.detectChanges();32 const compiled = fixture.debugElement.nativeElement;33 const router = ngMocks.findInstance(Router);34 const spy = spyOn(router, 'navigate');35 compiled.querySelector('button').click();36 expect(spy).toHaveBeenCalledWith(['']);37 });38});39{40 "compilerOptions": {41 },
Using AI Code Generation
1import { RouterTestingModule } from '@angular/router/testing';2import { TestBed } from '@angular/core/testing';3import { Router } from '@angular/router';4import { AppComponent } from './app.component';5describe('AppComponent', () => {6 let router: Router;7 beforeEach(async () => {8 await TestBed.configureTestingModule({9 imports: [RouterTestingModule],10 }).compileComponents();11 router = TestBed.inject(Router);12 });13 it('should create the app', () => {14 const fixture = TestBed.createComponent(AppComponent);15 const app = fixture.componentInstance;16 expect(app).toBeTruthy();17 });18 it('should have as title "test"', () => {19 const fixture = TestBed.createComponent(AppComponent);20 const app = fixture.componentInstance;21 expect(app.title).toEqual('test');22 });23 it('should render title', () => {24 const fixture = TestBed.createComponent(AppComponent);25 fixture.detectChanges();26 const compiled = fixture.nativeElement as HTMLElement;27 expect(compiled.querySelector('.content span')?.textContent).toContain(28 );29 });30 it('should navigate to "/test" when click on test button', () => {31 const fixture = TestBed.createComponent(AppComponent);32 fixture.detectChanges();33 const compiled = fixture.nativeElement as HTMLElement;34 const spy = spyOn(router, 'navigateByUrl');35 compiled.querySelector('button')?.click();36 expect(spy).toHaveBeenCalledWith('/test');37 });38});39import { RouterTestingModule } from '@angular/router/testing';40import { TestBed } from '@angular/core/testing';41import { Router } from '@angular/router';42import { AppComponent } from './app.component';43describe('AppComponent', () => {44 let router: Router;45 beforeEach(async () => {46 await TestBed.configureTestingModule({47 imports: [RouterTestingModule],48 }).compileComponents();49 router = TestBed.inject(Router);50 });51 it('should create the app', () => {52 const fixture = TestBed.createComponent(AppComponent);53 const app = fixture.componentInstance;54 expect(app).toBeTruthy();55 });56 it('should have as title "test"', () => {57 const fixture = TestBed.createComponent(AppComponent);58 const app = fixture.componentInstance;59 expect(app.title).toEqual('test');60 });61 it('should render title', () => {62 const fixture = TestBed.createComponent(AppComponent);
Using AI Code Generation
1var ngMocks = require('ng-mocks');2var test = ngMocks.test;3var router = ngMocks.router;4describe('router', function() {5 var $state;6 beforeEach(function() {7 $state = router.state;8 });9 it('should have a home state', function() {10 expect($state.get('home')).toBeDefined();11 });12 it('should have a about state', function() {13 expect($state.get('about')).toBeDefined();14 });15});
Using AI Code Generation
1import { RouterTestingModule } from '@angular/router/testing';2import { RouterTestingModule } from '@angular/router/testing';3import { MockComponent } from 'ng-mocks';4import { MockComponent } from 'ng-mocks';5import { MockRender } from 'ng-mocks';6import { MockRender } from 'ng-mocks';7import { MockDirective } from 'ng-mocks';8import { MockDirective } from 'ng-mocks';9import { MockRender } from 'ng-mocks';10import { MockRender } from 'ng-mocks';11import { MockPipe } from 'ng-mocks';12import { MockPipe } from 'ng-mocks';13import { MockRender } from 'ng-mocks';14import { MockRender } from 'ng-mocks';15import { MockModule } from 'ng-mocks';16import { MockModule } from 'ng-mocks';17import { MockRender } from 'ng-mocks';18import { MockRender } from 'ng-mocks';
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!