How to use logConfig method in ts-auto-mock

Best JavaScript code snippet using ts-auto-mock

updater.ts

Source:updater.ts Github

copy

Full Screen

1import fs from 'fs';2import mv from 'mv';3import path from 'path';4import ftp from 'jsftp';5import crypto from 'crypto';6import { RemoteFileInfo, LogConfig } from './types';7import { of, from, defer, Observable, iif, EMPTY } from 'rxjs';8import {9 map,10 catchError,11 toArray,12 mergeMap,13 concatMap,14 tap,15} from 'rxjs/operators';16import { logEntry } from './logger';17import {18 MainLogDownloadFilePercentageStatusSubject,19 MainLogDownloadFileProgressStatusSubject,20} from '../containers/main/observables';21import { BASE_URI, DOC_URI_GAMEPREFS } from '../constants';22/**23 * Type for FTP instance24 */25interface FTP extends ftp {26 auth(27 name: string,28 pass: string,29 callback: (err: Error | undefined) => void30 ): void;31}32const connection = {33 host: '51.222.29.196',34 user: 'ftploud',35 pass: 'ftploud123',36};37/**38 * Determine the default log configuration by environment39 */40const defaultLogConfig: LogConfig = {41 channels: (process.env.REACT_APP_LOG_CONFIG_CHANNELS ?? 'main,log,file')42 .split(',')43 .map((x) => x.trim()) as LogConfig['channels'],44};45/**46 * Create a local file URI from given baseURI and path47 * @param baseURI48 * @param path49 */50const updaterCreateLocalFileURI = (baseURI: string, path: string) =>51 `${baseURI}/LOUD/${path}`.replace('\\', '/').replace('//', '/').trim();52/**53 * Create a remote file path from a RemoteFileInfo54 * @param fileInfo55 */56const updaterCreateRemoteFileURI = (fileInfo: RemoteFileInfo) =>57 `${fileInfo.path},0x${fileInfo.hash},${fileInfo.size}`;58/**59 * Extract the local dir for a file60 * @param fileURI61 */62const updaterCreateLocalFileDirURI = (fileURI: string) => {63 const chunks = fileURI.split('/');64 chunks.pop();65 return chunks.join('/');66};67/**68 * Convenience function for parsing a line from a CRC file into a RemoteFileInfo instance69 * @param fileEntry70 */71const updaterStringToRemoteFileInfo = (fileEntry: string): RemoteFileInfo => {72 const fixedFileEntry = fileEntry.replace('\\', '/').trim();73 const [path, hexsha, size] = fixedFileEntry.split(',');74 return {75 path,76 hash: hexsha.substr(2),77 size: Number.parseInt(size),78 };79};80/**81 * Connect to the FTP server82 */83const updaterConnectFTP$ = () => {84 logEntry('updaterConnectFTP$:: Connecting to FTP...');85 return from<Promise<FTP>>(86 new Promise((res) => {87 const client: FTP = new ftp(connection) as FTP;88 client.on('connect', (err) => {89 if (err) {90 logEntry(`updaterConnectFTP$:connect:: ${err}`, 'error');91 throw err;92 }93 client.auth(connection.user!, connection.pass!, (errAuth) => {94 if (errAuth) {95 logEntry(`updaterConnectFTP$:auth:: ${errAuth}`, 'error');96 throw errAuth;97 }98 res(client);99 });100 });101 client.on('error', (err) => {102 logEntry(103 `updaterConnectFTP$:connect:: Could not connect to FTP ${err}`,104 'error'105 );106 throw err;107 });108 })109 );110};111/**112 * Fetch the CRC info from the server113 * @param logConfig114 */115const updaterGetCRCInfo$ = (logConfig: LogConfig = defaultLogConfig) =>116 from<Promise<string>>(117 new Promise((res) => {118 updaterConnectFTP$().subscribe(119 (client) => {120 logEntry(121 `updaterGetCRCInfo$:auth:: Successfully connected to FTP`,122 'log',123 logConfig.channels124 );125 client.get('LOUD/SCFA_FileInfo.txt', (err, socket) => {126 if (err) {127 logEntry(128 `updaterGetCRCInfo$:get:: ${err}`,129 'error',130 logConfig.channels131 );132 throw err;133 }134 let str = '';135 socket.on('data', (d) => {136 str += d;137 });138 socket.on('close', (errClose) => {139 if (errClose) {140 logEntry(141 `updaterGetCRCInfo$:close:: ${err}`,142 'error',143 logConfig.channels144 );145 throw errClose;146 }147 logEntry(148 `updaterGetCRCInfo$:get:: Succesfully retrieved CRC file from FTP`,149 'log',150 logConfig.channels151 );152 res(str);153 });154 socket.resume();155 });156 },157 (e) => {158 logEntry(159 `updaterGetCRCInfo$:connect/auth:: ${e}`,160 'error',161 logConfig.channels162 );163 }164 );165 })166 );167/**168 * Get a remote file from the server169 * @param fileInfo170 * @param client171 * @param logConfig172 */173const updaterGetRemoteFile$ = (174 fileInfo: RemoteFileInfo,175 client: FTP,176 logConfig: LogConfig = defaultLogConfig177) => {178 return from<Promise<Buffer>>(179 new Promise((res) => {180 client.get(`LOUD/${fileInfo.path}`, (err, socket) => {181 if (err) {182 logEntry(183 `updaterGetRemoteFile$:get:: ${err}`,184 'error',185 logConfig.channels186 );187 throw err;188 }189 logEntry(190 `updaterGetRemoteFile$:start:: Start downloading file ${fileInfo.path}, ${fileInfo.size}`,191 'log',192 logConfig.channels193 );194 MainLogDownloadFilePercentageStatusSubject.next(0);195 let bufferPercent = 0;196 let bufferLength = 0;197 const buffer: Buffer[] = [];198 socket.on('data', (d) => {199 buffer.push(d);200 201 bufferLength += d.byteLength202 let newBufferPercent = Math.floor((bufferLength / fileInfo.size) * 100);203 if(newBufferPercent !== bufferPercent)204 {205 bufferPercent = newBufferPercent;206 MainLogDownloadFilePercentageStatusSubject.next(bufferPercent);207 }208 });209 socket.on('close', (errClose) => {210 if (errClose) {211 logEntry(212 `updaterGetRemoteFile$:close:: ${err}`,213 'error',214 logConfig.channels215 );216 throw errClose;217 }218 res(Buffer.concat(buffer));219 });220 socket.resume();221 });222 })223 );224};225/**226 * Convenience method for fetching and writing multiple files from the FTP227 * @param baseURI228 * @param fileInfos229 * @param logConfig230 */231const updaterGetAndWriteRemoteFiles$ = (232 baseURI: string,233 fileInfos: RemoteFileInfo[],234 logConfig: LogConfig = defaultLogConfig235): Observable<[RemoteFileInfo[], RemoteFileInfo[]]> => {236 return new Observable((subscriber) => {237 const filesSucceeded: RemoteFileInfo[] = [];238 const filesFailed: RemoteFileInfo[] = [];239 return updaterConnectFTP$().subscribe(240 (c) => {241 from(fileInfos)242 .pipe(243 concatMap((fileInfo, fii) => {244 if (fii === 0) {245 MainLogDownloadFileProgressStatusSubject.next([246 fii + 1,247 fileInfos.length,248 ]);249 }250 return updaterGetRemoteFile$(fileInfo as RemoteFileInfo, c).pipe(251 mergeMap((buffer) =>252 updaterWriteBufferToLocalFile$(253 baseURI,254 fileInfo,255 buffer,256 logConfig257 ).pipe(258 map((fi) => {259 return [fi, true] as [RemoteFileInfo, boolean];260 }),261 tap(() => {262 MainLogDownloadFileProgressStatusSubject.next([263 Math.min(fii + 2, fileInfos.length),264 fileInfos.length,265 ]);266 })267 )268 ),269 catchError((e) => {270 logEntry(271 `updaterGetAndWriteRemoteFiles$:: ${e}`,272 'error',273 logConfig.channels274 );275 return of([fileInfo, false] as [RemoteFileInfo, boolean]);276 })277 );278 })279 )280 .subscribe(281 ([fileInfo, success]) => {282 if (success) {283 filesSucceeded.push(fileInfo);284 } else {285 filesFailed.push(fileInfo);286 }287 },288 (e) => {289 logEntry(`updaterGetAndWriteRemoteFiles$::inner: ${e}`);290 },291 () => {292 subscriber.next([filesSucceeded, filesFailed]);293 subscriber.complete();294 }295 );296 },297 (e) => {298 logEntry(`updaterGetAndWriteRemoteFiles$::outer: ${e}`);299 subscriber.error(e);300 }301 );302 });303};304/**305 * Write a buffer to a local file306 * @param uri307 * @param fileInfo308 * @param buffer309 * @param logConfig310 */311const updaterWriteBufferToLocalFile$ = (312 uri: string,313 fileInfo: RemoteFileInfo,314 buffer: Buffer,315 logConfig: LogConfig = defaultLogConfig316) => {317 return from(318 new Promise<RemoteFileInfo>((res, rej) => {319 const path = updaterCreateLocalFileURI(uri, fileInfo.path);320 const dir = updaterCreateLocalFileDirURI(path);321 logEntry(322 `Writing file ${path}, ${fileInfo.size}`,323 'log',324 logConfig.channels325 );326 fs.mkdir(dir, { recursive: true }, (err) => {327 if (err) {328 logEntry(329 `updaterWriteBufferToLocalFile$:mkdir::${fileInfo.path},${buffer.length} / ${err}`,330 'error',331 logConfig.channels332 );333 throw err;334 }335 fs.writeFile(path, buffer, (errWrite) => {336 if (errWrite) {337 logEntry(338 `updaterWriteBufferToLocalFile$:mkdir::${fileInfo.path},${buffer.length} / ${errWrite}`,339 'error',340 logConfig.channels341 );342 throw errWrite;343 }344 logEntry(345 `updaterWriteBufferToLocalFile$:done:: Successfully written file ${fileInfo.path},${buffer.length}`,346 'log',347 logConfig.channels.filter((channel) => channel !== 'main')348 );349 res(fileInfo);350 });351 });352 })353 );354};355/**356 * Generate RemoteFileInfo from the remote CRC files' content357 * @param remoteFileContent358 */359const updaterParseRemoteFileContent = (360 remoteFileContent: string361): RemoteFileInfo[] =>362 remoteFileContent363 .replace(/\\+/gi, '/')364 .replace(/^\s+|\s+$/g, '')365 .split(/\r?\n/)366 .map((line) => updaterStringToRemoteFileInfo(line));367/**368 * Retrieve a buffer from a local file369 * @param path370 * @param logConfig371 */372const updaterLocalFileData$ = (373 path: string,374 logConfig: LogConfig = defaultLogConfig375): Observable<Buffer> =>376 defer(() =>377 from<Promise<Buffer>>(378 new Promise((res, rej) => {379 fs.readFile(path, (err, data) => {380 if (err) {381 logEntry(`${err}`, 'error', logConfig.channels);382 rej(err);383 }384 res(data);385 });386 })387 )388 );389/**390 * Compare given [[RemoteFileInfo]] to local counterpart391 * @param fileInfo392 */393const updaterCompareRemoteFileInfo$ = (394 fileInfo: RemoteFileInfo,395 baseURI: string,396 logConfig: LogConfig = defaultLogConfig397): Observable<[RemoteFileInfo, boolean]> =>398 of(fileInfo).pipe(399 concatMap((info) =>400 updaterLocalFileData$(401 updaterCreateLocalFileURI(baseURI, fileInfo.path),402 logConfig403 ).pipe(404 map((data) => {405 if (406 info.path.toLowerCase().includes('louddatapath.lua') &&407 data.byteLength408 ) {409 return true;410 }411 const shacrypto = crypto.createHash('sha1');412 shacrypto.update(data);413 const result = shacrypto.digest('hex').toUpperCase();414 shacrypto.destroy();415 const resultBoolean =416 result === info.hash && data.byteLength === info.size;417 return resultBoolean;418 }),419 map((result) => [info, result] as [RemoteFileInfo, boolean]),420 tap(([info, result]) => {421 logEntry(422 `CompareRemoteFileInfo$::${updaterCreateRemoteFileURI(423 info424 )} / ${result}`,425 'log',426 logConfig.channels.filter((channel) => channel !== 'main')427 );428 })429 )430 ),431 catchError((err) => {432 logEntry(433 `CompareRemoteFileInfo$::${updaterCreateRemoteFileURI(434 fileInfo435 )} / ${err}`,436 'error',437 logConfig.channels438 );439 return of([fileInfo, false] as [RemoteFileInfo, boolean]);440 })441 );442/**443 * Determine which files are out of sync by comparing the remote CRC with a locally created CRC.444 * @param fileInfos445 * @param baseURI446 * @param logConfig447 */448const updaterCollectOutOfSyncFiles$ = (449 fileInfos: RemoteFileInfo[],450 baseURI: string,451 logConfig: LogConfig = defaultLogConfig452) => {453 logEntry(454 'updaterCollectOutOfSyncFiles$:: Start gathering files that are out-of-sync'455 );456 return from(fileInfos).pipe(457 concatMap((info) =>458 updaterCompareRemoteFileInfo$(info, baseURI, logConfig).pipe(459 mergeMap(([info, result]) => iif(() => !!result, EMPTY, of(info)))460 )461 ),462 toArray()463 );464};465/**466 * Excluded partial paths from the CRC creator467 */468const excludeCRC = [469 'louddatapath.lua',470 '.unsupported',471 'usermaps',472 'usermods',473 'usergamedata',474 'loud.log',475 '.scfareplay',476];477/**478 * Create a local CRC to be used as a source on the server479 */480const updaterCreateLocalCRC$ = (logConfig = defaultLogConfig) => {481 logEntry('updaterCreateLocalCRC$:: Starting the CRC Process');482 return from(483 new Promise((res, rej) => {484 const walk = (485 dir: string,486 done: (err: Error | null, results?: string[]) => void487 ) => {488 var results: string[] = [];489 fs.readdir(dir, (err, list) => {490 if (err) {491 return done(err);492 }493 var pending = list.length;494 if (!pending) {495 return done(null, results);496 }497 list.forEach((file) => {498 file = path.resolve(dir, file);499 fs.stat(file, (_err, stat) => {500 if (stat && stat.isDirectory()) {501 walk(file, (_err, res) => {502 results = results.concat(res!);503 if (!--pending) done(null, results);504 });505 } else {506 results.push(file);507 if (!--pending) done(null, results);508 }509 });510 });511 });512 };513 walk(`${BASE_URI}/LOUD`, (err, results) => {514 if (err || !results) {515 logEntry(516 `updaterCreateLocalCRC$:walk::${err} / ${results}`,517 'error',518 logConfig.channels519 );520 rej(err);521 return;522 }523 const crcs = results524 .filter((res) => {525 return !excludeCRC.find((ex) => res.toLowerCase().includes(ex));526 })527 .map((result) => {528 const buffer = fs.readFileSync(result);529 const fileURI = path530 .normalize(result)531 .replace(path.normalize(`${BASE_URI}/LOUD/`), '');532 const shacrypto = crypto.createHash('sha1');533 shacrypto.update(buffer);534 const sha1 = shacrypto.digest('hex').toUpperCase();535 shacrypto.destroy();536 return `${fileURI},0x${sha1},${buffer.byteLength}`;537 });538 crcs.push(539 'bin\\LoudDataPath.lua,0xE0A4D83007A0222CD1EDBD77E6CFA81BB2F32252,1499'540 );541 crcs.sort();542 fs.writeFile(543 `${BASE_URI}/SCFA_FileInfo.txt`,544 crcs.join('\r\n'),545 (err) => {546 if (err) {547 logEntry(548 `Could not generate CRC file ${err}`,549 'error',550 logConfig.channels551 );552 rej(err);553 return;554 }555 logEntry(556 'updaterCreateLocalCRC$:: Finished the CRC Process. The file is located at ./SCFA_FileInfo.txt',557 'log',558 logConfig.channels559 );560 // @ts-ignore561 res();562 }563 );564 });565 })566 );567};568const updaterCleanupGameData$ = (569 fileInfos: RemoteFileInfo[],570 logConfig = defaultLogConfig571) => {572 logEntry(573 'updaterCleanupGamedata$:: Starting gamedata cleanup',574 'log',575 logConfig.channels.filter((channel) => channel !== 'main')576 );577 const gamedataInCRC = fileInfos.reduce((acc, fi) => {578 if (fi.path.startsWith('gamedata')) {579 acc.push(fi.path.replace(/\//g, '\\').split('\\')[1]);580 }581 return acc;582 }, [] as string[]);583 return from(584 new Promise((res) => {585 fs.statSync(`${BASE_URI}/LOUD/gamedata`);586 fs.readdir(`${BASE_URI}/LOUD/gamedata`, (err, entries) => {587 if (err) {588 logEntry(589 `updaterCleanupGamedata$:: ${err}`,590 'error',591 logConfig.channels592 );593 }594 const falseEntries = entries.filter((e) => !gamedataInCRC.includes(e));595 for (let entry of falseEntries) {596 if (entry.toLowerCase().includes('advanced strategic icons')) {597 logEntry(598 `updaterCleanupGamedata$:mv:: Skipping Advanced strategic icons`,599 'log',600 ['file', 'log']601 );602 continue;603 }604 if (605 entry.toLowerCase().includes('lua') &&606 !entry.toLowerCase().includes('.scd')607 ) {608 logEntry(609 `updaterCleanupGamedata$:mv:: Skipping generated LUA`,610 'log',611 ['file', 'log']612 );613 continue;614 }615 fs.unlink(`${BASE_URI}/LOUD/gamedata/${entry}`, (errMv) => {616 if (errMv) {617 logEntry(`updaterCleanupGamedata$:mv:: ${errMv}`);618 }619 });620 }621 res(!!falseEntries.length);622 });623 })624 );625};626const updaterCleanupMaps$ = (627 fileInfos: RemoteFileInfo[],628 logConfig = defaultLogConfig629) => {630 logEntry(631 'updaterCleanupMaps$:: Starting Maps cleanup',632 'log',633 logConfig.channels.filter((channel) => channel !== 'main')634 );635 const mapsInCRC = fileInfos.reduce((acc, fi) => {636 if (fi.path.startsWith('maps')) {637 acc.push(fi.path.replace(/\//g, '\\').split('\\')[1]);638 }639 return acc;640 }, [] as string[]);641 return from(642 new Promise((res) => {643 fs.statSync(`${BASE_URI}/LOUD/maps`);644 fs.readdir(`${BASE_URI}/LOUD/maps`, (err, entries) => {645 if (err) {646 logEntry(`updaterCleanupMaps$:: ${err}`, 'error', logConfig.channels);647 }648 const falseEntries = entries.filter((e) => !mapsInCRC.includes(e));649 if (falseEntries.length) {650 logEntry(651 `updaterCleanupMaps$:: Found extraneous items ${JSON.stringify(652 falseEntries653 )}. Moving to maps.unsupported.`,654 'log',655 logConfig.channels656 );657 logEntry(658 'External maps and mods are to be placed in your "<Drive>:\\Users\\<your account>\\My Games\\Gas Powered Games\\Maps / Mods" folders and will be only loaded if they are toggled on in the launcher',659 'warn',660 logConfig.channels661 );662 }663 if (!falseEntries.length) {664 // @ts-ignore665 res();666 return;667 }668 fs.mkdirSync(`${BASE_URI}/LOUD/maps.unsupported`, { recursive: true });669 for (let entry of falseEntries) {670 mv(671 `${BASE_URI}/LOUD/maps/${entry}`,672 `${BASE_URI}/LOUD/maps.unsupported/${entry}`,673 (errMv) => {674 if (errMv) {675 logEntry(`updaterCleanupMaps$:mv:: ${errMv}`);676 }677 }678 );679 }680 res(!!falseEntries.length);681 });682 })683 );684};685const updaterCleanupMods$ = (logConfig = defaultLogConfig) => {686 logEntry(687 'updaterCleanupMods$:: Starting Mods cleanup',688 'log',689 logConfig.channels.filter((channel) => channel !== 'main')690 );691 return from(692 new Promise((res) => {693 fs.stat(`${BASE_URI}/LOUD/mods`, (err) => {694 if (err) {695 if (err.message.includes('ENOENT')) {696 // @ts-ignore697 res();698 return;699 }700 logEntry(`${err}`, 'error', logConfig.channels);701 throw err;702 }703 const entries = fs.readdirSync(`${BASE_URI}/LOUD/mods`);704 if (entries.length) {705 logEntry(706 'External maps and mods are to be placed in your "<Drive>:\\Users\\<your account>\\My Games\\Gas Powered Games\\Maps / Mods" folders and will be only loaded if they are toggled on in the launcher',707 'warn',708 logConfig.channels709 );710 }711 fs.mkdir(`${BASE_URI}/LOUD/mods.unsupported`, () => {712 for (let entry of entries) {713 mv(714 `${BASE_URI}/LOUD/mods/${entry}`,715 `${BASE_URI}/LOUD/mods.unsupported/${entry}`,716 (err) => {717 if (err) {718 logEntry(719 `updaterCleanupMods$:: ${err}`,720 'error',721 logConfig.channels722 );723 }724 }725 );726 }727 });728 });729 })730 );731};732const updaterCleanupUserprefs$ = (logConfig = defaultLogConfig) => {733 logEntry(734 'updaterCleanupGameprefs$:: Starting user preferences cleanup',735 'log',736 logConfig.channels.filter((channel) => channel !== 'main')737 );738 return from(739 new Promise((res, rej) => {740 fs.statSync(DOC_URI_GAMEPREFS);741 const buffer = fs.readFileSync(DOC_URI_GAMEPREFS);742 let fileStr = buffer.toString();743 fileStr = fileStr.replace(/fidelity = \d/g, 'fidelity = 2');744 fileStr = fileStr.replace(/shadow_quality = \d/g, 'shadow_quality = 3');745 fileStr = fileStr.replace(/texture_level = \d/g, 'texture_level = 2');746 fileStr = fileStr.replace(/level_of_detail = \d/g, 'level_of_detail = 2');747 fs.writeFileSync(DOC_URI_GAMEPREFS, fileStr);748 // @ts-ignore749 res();750 })751 );752};753export {754 updaterCleanupGameData$,755 updaterCleanupMaps$,756 updaterCleanupMods$,757 updaterCleanupUserprefs$,758 updaterCreateLocalCRC$,759 updaterConnectFTP$,760 updaterGetCRCInfo$,761 updaterParseRemoteFileContent,762 updaterCompareRemoteFileInfo$,763 updaterStringToRemoteFileInfo,764 updaterLocalFileData$,765 updaterCollectOutOfSyncFiles$,766 updaterGetRemoteFile$,767 updaterWriteBufferToLocalFile$,768 updaterGetAndWriteRemoteFiles$,...

Full Screen

Full Screen

override-console-log.js

Source:override-console-log.js Github

copy

Full Screen

1/*2Author: Shammi Hans | Smi00013Dependency: JavaScript (ES06)4Description: Overriding console.log to customize the log with current time along with passed log arguments5*/6const origlog = console.log;7const defaultOptions = Object.freeze(8 {9 logDate: false,10 logDateFormat: 'toLocaleString', // Date format is actually the format-function-name in which user wants to convert the date11 enableAll: true,12 enableLog: true,13 enableLogI: true,14 enableLogD: true,15 enableLogE: true,16 logCustomPrefix: '', // accepts any string of length < 100017 logDateThenPrefix: true,18 debugPrefix: 'DEBUG:',19 infoPrefix: 'INFO:',20 errorPrefix: 'ERROR:',21 warmPrefix: 'WARNING:',22 stopLogging: false // stop this logging with format, only console.log() & log() can be used as usual logging23 }24);25let logConfig = {};26console.resetLogger = function() {27 logConfig = JSON.parse(JSON.stringify(defaultOptions));28};29console.resetLogger();30const getCurrentDateFormat = function() {31 var dateStr = new Date().toLocaleString(); // default date format32 if (logConfig && logConfig.logDateFormat && typeof logConfig.logDateFormat === 'string') {33 switch (logConfig.logDateFormat.toLowerCase()) {34 case 'todatestring':35 dateStr = (new Date()).toDateString();36 break;37 case 'togmtstring':38 dateStr = (new Date()).toGMTString();39 break;40 case 'toisostring':41 dateStr = (new Date()).toISOString();42 break;43 case 'tojson':44 dateStr = (new Date()).toJSON();45 break;46 case 'tolocaledatestring':47 dateStr = (new Date()).toLocaleDateString();48 break;49 case 'todatestring':50 dateStr = (new Date()).toLocaleTimeString();51 break;52 case 'tostring':53 dateStr = (new Date()).toString();54 break;55 case 'totimestring':56 dateStr = (new Date()).toTimeString();57 break;58 case 'toutcstring':59 dateStr = (new Date()).toUTCString();60 break;61 default:62 // dateStr = (new Date()).toLocaleString();63 break;64 }65 }66 return dateStr + ' ';67};68console.log = function (obj, ...argumentArray) {69 var dateString = '';70 var datePrefix = '';71 if (logConfig && !logConfig.stopLogging) {72 if (logConfig && logConfig.enableAll && logConfig.enableLog && logConfig.logDate) {73 dateString = getCurrentDateFormat();74 var prefix = '';75 if (typeof logConfig.logCustomPrefix === 'string' && logConfig.logCustomPrefix.length < 1000 ) {76 prefix = logConfig.logCustomPrefix;77 }78 datePrefix = logConfig.logDateThenPrefix ? (dateString + prefix + ' ') : (prefix + ' ' + dateString);79 }80 }81 if (typeof obj === 'string') {82 argumentArray.unshift(datePrefix + obj);83 } else {84 // This handles console.log( object )85 argumentArray.unshift(obj);86 argumentArray.unshift(datePrefix);87 }88 origlog.apply(this, argumentArray);89};90const getDatePrefix = function(prefix) {91 var datePrefix = '';92 var dateString = '';93 if (logConfig && logConfig.enableAll) {94 if (logConfig.logDate) {95 dateString = getCurrentDateFormat();96 }97 datePrefix = logConfig.logDateThenPrefix ? (dateString + prefix + ' ') : (prefix + ' ' + dateString);98 }99 return datePrefix + ' ';100};101console.logD = function (obj, ...argumentArray) {102 if (logConfig && !logConfig.stopLogging) {103 var datePrefix = (logConfig && logConfig.enableLogD) ?104 getDatePrefix(logConfig.debugPrefix) :105 '';106 if (typeof obj === 'string') {107 argumentArray.unshift(datePrefix + obj);108 } else {109 argumentArray.unshift(obj);110 argumentArray.unshift(datePrefix);111 }112 origlog.apply(this, argumentArray);113 }114};115console.logW = function (obj, ...argumentArray) {116 var origlog = console.warn;117 if (logConfig && !logConfig.stopLogging) {118 var datePrefix = (logConfig && logConfig.enableLogD) ?119 getDatePrefix(logConfig.warmPrefix) :120 '';121 if (typeof obj === 'string') {122 argumentArray.unshift(datePrefix + obj);123 } else {124 argumentArray.unshift(obj);125 argumentArray.unshift(datePrefix);126 }127 origlog.apply(this, argumentArray);128 }129};130console.logI = function (obj, ...argumentArray) {131 var origlog = console.info;132 if (logConfig && !logConfig.stopLogging) {133 var datePrefix = (logConfig && logConfig.enableLogI) ?134 getDatePrefix(logConfig.infoPrefix) :135 '';136 if (typeof obj === 'string') {137 argumentArray.unshift(datePrefix + obj);138 } else {139 argumentArray.unshift(obj);140 argumentArray.unshift(datePrefix);141 }142 origlog.apply(this, argumentArray);143 }144};145console.logE = function (obj, ...argumentArray) {146 var origlog = console.error;147 if (logConfig && !logConfig.stopLogging) {148 var datePrefix = (logConfig && logConfig.enableLogE) ?149 getDatePrefix(logConfig.errorPrefix) :150 '';151 if (typeof obj === 'string') {152 argumentArray.unshift(datePrefix + obj);153 } else {154 // This handles console.log( object )155 argumentArray.unshift(obj);156 argumentArray.unshift(datePrefix);157 }158 origlog.apply(this, argumentArray);159 }160};161module.exports.log = console.log;162module.exports.logI = console.logI;163module.exports.logD = console.logD;164module.exports.logW = console.logW;165module.exports.logE = console.logE;166module.exports.logConfig = logConfig;...

Full Screen

Full Screen

forum.router.js

Source:forum.router.js Github

copy

Full Screen

1const router = require('express').Router();2const logger = require('../../services/app.logger');3const forumCtrl = require('./forum.controller');4const appConfig = require('../../config').app;5const logConfig = require('../../config/loggerConstants');6//post forum questions in a database7router.post('/', function(req, res) {8 let forumData = req.body;9 try {10 forumCtrl.addPost(forumData).then((successResult) => {11 logger.info(logConfig.POST_FORUM_QUESTION);12 return res.json({ status: 201, message: logConfig.POST_FORUM_QUESTION, data: successResult });13 }, (errResult) => {14 logger.error(errResult);15 return res.json({ status: 200, message: logConfig.POST_FORUM_QUESTION_ERROR, data: errResult });16 });17 } catch (err) {18 logger.fatal(logConfig.EXCEPTION_FOUND + err);19 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });20 }21});22//get forum question from database23router.get('/', function(req, res) {24 try {25 forumCtrl.getPost().then((successResult) => {26 logger.info(logConfig.GET_FORUM_QUESTION);27 return res.json({ status: 201, message: logConfig.GET_FORUM_QUESTION, data: successResult });28 }, (errResult) => {29 logger.error(errResult);30 return res.json({ status: 200, message: logConfig.GET_FORUM_QUESTION_ERROR, data: errResult });31 });32 } catch (err) {33 logger.fatal(logConfig.EXCEPTION_FOUND + err);34 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });35 }36});37//search forum questions from database38router.get('/term/:searchTerm', function(req, res) {39 let getValue = req.params.searchTerm;40 try {41 forumCtrl.getSearch(getValue).then((successResult) => {42 logger.info(logConfig.SEARCH_FORUM_QUESTION);43 return res.json({ status: 201, message: logConfig.SEARCH_FORUM_QUESTION, data: successResult });44 }, (errResult) => {45 logger.error(errResult);46 return res.json({ status: 200, message: logConfig.SEARCH_FORUM_QUESTION_ERROR, data: errResult });47 });48 } catch (err) {49 logger.fatal(logConfig.EXCEPTION_FOUND + err);50 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });51 }52});53//get the question detail from database54router.get('/:id', function(req, res) {55 let id = req.params.id;56 try {57 forumCtrl.getPostById(id).then((successResult) => {58 logger.info(logConfig.GET_DATA_FROM_ID);59 return res.json({ status: 201, message: logConfig.GET_DATA_FROM_ID, data: successResult });60 }, (errResult) => {61 logger.error(errResult);62 return res.json({ status: 200, message: logConfig.GET_DATA_FROM_ID_ERROR, data: errResult });63 });64 } catch (err) {65 logger.fatal(logConfig.EXCEPTION_FOUND + err);66 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });67 }68});69//add answers to paticular forum question70router.put('/:id', (req, res) => {71 let getValue = req.params.id;72 let forumUpdate = req.body;73 try {74 forumCtrl.saveAnswer(getValue, forumUpdate).then((successResult) => {75 logger.info(logConfig.ADD_ANSWER_ON_QUESTION);76 return res.json({ status: 201, message: logConfig.ADD_ANSWER_ON_QUESTION, data: successResult });77 }, (errResult) => {78 logger.error(errResult);79 return res.json({ status: 200, message: logConfig.ADD_ANSWER_ON_QUESTION_ERROR, data: errResult });80 });81 } catch (err) {82 logger.fatal(logConfig.EXCEPTION_FOUND + err);83 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });84 }85});86//add likes to paticular question post87router.put('/like/:id', (req, res) => {88 let getValue = req.params.id;89 let forumUpdate = req.body;90 try {91 forumCtrl.saveLike(getValue, forumUpdate).then((successResult) => {92 logger.info(logConfig.ADD_LIKES_ON_QUESTION);93 return res.json({ status: 201, message: logConfig.ADD_LIKES_ON_QUESTION, data: successResult });94 }, (errResult) => {95 logger.error(errResult);96 return res.json({ status: 200, message: logConfig.ADD_LIKES_ON_QUESTION_ERROR, data: errResult });97 });98 } catch (err) {99 logger.fatal(logConfig.EXCEPTION_FOUND + err);100 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });101 }102});103//add dislikes to paticular question post104router.put('/dislike/:id', (req, res) => {105 let getValue = req.params.id;106 let forumUpdate = req.body;107 try {108 forumCtrl.saveDislike(getValue, forumUpdate).then((successResult) => {109 logger.info(logConfig.ADD_DISLIKE_ON_QUESTION);110 return res.json({ status: 201, message: logConfig.ADD_DISLIKE_ON_QUESTION, data: successResult });111 }, (errResult) => {112 logger.error(errResult);113 return res.json({ status: 200, message: logConfig.ADD_DISLIKE_ON_QUESTION_ERROR, data: errResult });114 });115 } catch (err) {116 logger.fatal(logConfig.EXCEPTION_FOUND + err);117 return res.json({ status: 500, message: logConfig.EXCEPTION_FOUND, data: err });118 }119});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const logConfig = require('ts-auto-mock/logConfig');2logConfig({logLevel: 'debug', logToFile: true});3const logConfig = require('ts-auto-mock/logConfig');4logConfig({logLevel: 'debug', logToFile: true});5const logConfig = require('ts-auto-mock/logConfig');6logConfig({logLevel: 'debug', logToFile: true});7const logConfig = require('ts-auto-mock/logConfig');8logConfig({logLevel: 'debug', logToFile: true});9const logConfig = require('ts-auto-mock/logConfig');10logConfig({logLevel: 'debug', logToFile: true});11const logConfig = require('ts-auto-mock/logConfig');12logConfig({logLevel: 'debug', logToFile: true});13const logConfig = require('ts-auto-mock/logConfig');14logConfig({logLevel: 'debug', logToFile: true});15const logConfig = require('ts-auto-mock/logConfig');16logConfig({logLevel: 'debug', logToFile: true});17const logConfig = require('ts-auto-mock/logConfig');18logConfig({logLevel: 'debug', logToFile: true});19const logConfig = require('ts-auto-mock/logConfig');20logConfig({logLevel: 'debug', logToFile: true});21const logConfig = require('ts-auto-mock/logConfig');22logConfig({logLevel: 'debug', logToFile: true});23const logConfig = require('ts-auto-mock/logConfig');24logConfig({logLevel: 'debug', logToFile: true});25const logConfig = require('ts-auto-mock/logConfig');26logConfig({logLevel: 'debug', logToFile: true});27const logConfig = require('ts-auto-mock/logConfig');28logConfig({logLevel: 'debug', logToFile: true});29const logConfig = require('ts-auto-mock/logConfig');30logConfig({logLevel: 'debug',

Full Screen

Using AI Code Generation

copy

Full Screen

1import { logConfig } from 'ts-auto-mock';2logConfig({3});4import { logConfig } from 'ts-auto-mock';5logConfig({6});7import { logConfig } from 'ts-auto-mock';8logConfig({9});10import './ts-auto-mock.ts';11import './ts-auto-mock.ts';12import { logConfig } from '

Full Screen

Using AI Code Generation

copy

Full Screen

1import { logConfig } from 'ts-auto-mock';2logConfig({3});4logConfig({5});6logConfig({7});8logConfig();9logConfig({10});11logConfig({12});13logConfig({14});15logConfig({16});17logConfig({18});19logConfig({20});21logConfig({22});23logConfig({24});25logConfig({26});27logConfig({28});29logConfig({30});31logConfig({32});33logConfig({34});35logConfig({

Full Screen

Using AI Code Generation

copy

Full Screen

1import {logConfig} from 'ts-auto-mock';2logConfig({3});4import {logConfig} from 'ts-auto-mock';5logConfig({6});7Error Description Cannot find type information for ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for ... in ... The compiler cannot find the type information for the specified type. This error occurs when the type is not imported or it is not defined in the file. Cannot find type information for

Full Screen

Using AI Code Generation

copy

Full Screen

1import {logConfig} from 'ts-auto-mock';2logConfig({3});4import {logConfig} from 'ts-auto-mock';5logConfig({6});7import {logConfig} from 'ts-auto-mock';8logConfig({9});10import {logConfig} from 'ts-auto-mock';11logConfig({12});13import {logConfig} from 'ts-auto-mock';14logConfig({15});16import {logConfig} from 'ts-auto-mock';17logConfig({18});19import {logConfig} from 'ts-auto-mock';20logConfig({21});22import {logConfig} from 'ts-auto-mock';23logConfig({24});25import {logConfig} from 'ts-auto-mock';26logConfig({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { logConfig } = require('ts-auto-mock');2logConfig({3});4const { logConfig } = require('ts-auto-mock');5logConfig({6});7const { logConfig } = require('ts-auto-mock');8logConfig({9});10const { logConfig } = require('ts-auto-mock');11logConfig({12});13const { logConfig } = require('ts-auto-mock');14logConfig({

Full Screen

Using AI Code Generation

copy

Full Screen

1logConfig({2});3logConfig({4});5logConfig({6});7logConfig({8});9logConfig({

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ts-auto-mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful