Best JavaScript code snippet using storybook-root
admin.js
Source:admin.js
1const fs = require("fs").promises;2const path = require("path");3const child = require('child_process');4const express = require('express');5const auth = require('./auth');6const config = require('../state/config');7const mStreamServer = require('../server');8const dbQueue = require('../db/task-queue');9const logger = require('../logger');10const db = require('../db/manager');11const syncthing = require('../state/syncthing');12exports.loadFile = async (file) => {13 return JSON.parse(await fs.readFile(file, 'utf-8'));14}15exports.saveFile = async (saveData, file) => {16 return await fs.writeFile(file, JSON.stringify(saveData, null, 2), 'utf8')17}18exports.addDirectory = async (directory, vpath, autoAccess, isAudioBooks, mstream) => {19 // confirm directory is real20 const stat = await fs.stat(directory);21 if (!stat.isDirectory()) { throw `${directory} is not a directory` };22 if (config.program.folders[vpath]) { throw `'${vpath}' is already loaded into memory`; }23 // This extra step is so we can handle the process like a SQL transaction24 // The new var is a copy so the original program isn't touched25 // Once the file save is complete, the new user will be added26 const memClone = JSON.parse(JSON.stringify(config.program.folders));27 memClone[vpath] = { root: directory };28 if (isAudioBooks) { memClone[vpath].type = 'audio-books'; }29 // add directory to config file30 const loadConfig = await this.loadFile(config.configFile);31 loadConfig.folders = memClone;32 if (autoAccess === true) {33 const memCloneUsers = JSON.parse(JSON.stringify(config.program.users));34 Object.values(memCloneUsers).forEach(user => {35 user.vpaths.push(vpath);36 });37 loadConfig.users = memCloneUsers;38 }39 await this.saveFile(loadConfig, config.configFile);40 // add directory to program41 config.program.folders[vpath] = memClone;42 if (autoAccess === true) {43 Object.values(config.program.users).forEach(user => {44 user.vpaths.push(vpath);45 });46 }47 // add directory to server routing48 mstream.use(`/media/${vpath}/`, express.static(directory));49}50exports.removeDirectory = async (vpath) => {51 if (!config.program.folders[vpath]) { throw `'${vpath}' not found`; }52 const memCloneFolders = JSON.parse(JSON.stringify(config.program.folders));53 delete memCloneFolders[vpath];54 const memCloneUsers = JSON.parse(JSON.stringify(config.program.users));55 Object.values(memCloneUsers).forEach(user => {56 if (user.vpaths.includes(vpath)) {57 user.vpaths.splice(user.vpaths.indexOf(vpath), 1);58 }59 });60 const loadConfig = await this.loadFile(config.configFile);61 loadConfig.folders = memCloneFolders;62 loadConfig.users = memCloneUsers;63 await this.saveFile(loadConfig, config.configFile);64 db.getFileCollection().findAndRemove({ 'vpath': { '$eq': vpath } });65 db.saveFilesDB();66 // reboot server67 mStreamServer.reboot();68}69exports.addUser = async (username, password, admin, vpaths) => {70 if (config.program.users[username]) { throw `'${username}' is already loaded into memory`; }71 72 // hash password73 const hash = await auth.hashPassword(password);74 const newUser = {75 vpaths: vpaths,76 password: hash.hashPassword,77 salt: hash.salt,78 admin: admin79 };80 // This extra step is so we can handle the process like a SQL transaction81 // The new var is a copy so the original program isn't touched82 // Once the file save is complete, the new user will be added83 const memClone = JSON.parse(JSON.stringify(config.program.users));84 memClone[username] = newUser;85 const loadConfig = await this.loadFile(config.configFile);86 loadConfig.users = memClone;87 await this.saveFile(loadConfig, config.configFile);88 config.program.users[username] = newUser;89 // TODO: add user from scrobbler90}91exports.deleteUser = async (username) => {92 if (!config.program.users[username]) { throw `'${username}' does not exist`; }93 const memClone = JSON.parse(JSON.stringify(config.program.users));94 delete memClone[username];95 const loadConfig = await this.loadFile(config.configFile);96 loadConfig.users = memClone;97 await this.saveFile(loadConfig, config.configFile);98 delete config.program.users[username];99 db.getUserMetadataCollection().findAndRemove({ 'user': { '$eq': username } });100 db.saveUserDB();101 db.getPlaylistCollection().findAndRemove({ 'user': { '$eq': username } });102 db.saveUserDB();103 db.getShareCollection().findAndRemove({ 'user': { '$eq': username } });104 db.saveUserDB();105 // TODO: Remove user from scrobbler106}107exports.editUserPassword = async (username, password) => {108 if (!config.program.users[username]) { throw `'${username}' does not exist`; }109 const hash = await auth.hashPassword(password);110 const memClone = JSON.parse(JSON.stringify(config.program.users));111 memClone[username].password = hash.hashPassword;112 memClone[username].salt = hash.salt;113 const loadConfig = await this.loadFile(config.configFile);114 loadConfig.users = memClone;115 await this.saveFile(loadConfig, config.configFile);116 config.program.users[username].password = hash.hashPassword;117 config.program.users[username].salt = hash.salt;118}119exports.editUserVPaths = async (username, vpaths) => {120 if (!config.program.users[username]) { throw `'${username}' does not exist`; }121 const memClone = JSON.parse(JSON.stringify(config.program.users));122 memClone[username].vpaths = vpaths;123 const loadConfig = await this.loadFile(config.configFile);124 loadConfig.users = memClone;125 await this.saveFile(loadConfig, config.configFile);126 config.program.users[username].vpaths = vpaths;127}128exports.editUserAccess = async (username, admin) => {129 if (!config.program.users[username]) { throw `'${username}' does not exist`; }130 const memClone = JSON.parse(JSON.stringify(config.program.users));131 memClone[username].admin = admin;132 const loadConfig = await this.loadFile(config.configFile);133 loadConfig.users = memClone;134 await this.saveFile(loadConfig, config.configFile);135 config.program.users[username].admin = admin;136}137exports.editPort = async (port) => {138 if (config.program.port === port) { return; }139 const loadConfig = await this.loadFile(config.configFile);140 loadConfig.port = port;141 await this.saveFile(loadConfig, config.configFile);142 // reboot server143 mStreamServer.reboot();144}145exports.editMaxRequestSize = async (maxRequestSize) => {146 if (config.program.maxRequestSize === maxRequestSize) { return; }147 const loadConfig = await this.loadFile(config.configFile);148 loadConfig.maxRequestSize = maxRequestSize;149 await this.saveFile(loadConfig, config.configFile);150 // reboot server151 mStreamServer.reboot();152}153exports.editUpload = async (val) => {154 const loadConfig = await this.loadFile(config.configFile);155 loadConfig.noUpload = val;156 await this.saveFile(loadConfig, config.configFile);157 config.program.noUpload = val;158}159exports.editAddress = async (val) => {160 const loadConfig = await this.loadFile(config.configFile);161 loadConfig.address = val;162 await this.saveFile(loadConfig, config.configFile);163 mStreamServer.reboot();164}165exports.editSecret = async (val) => {166 const loadConfig = await this.loadFile(config.configFile);167 loadConfig.secret = val;168 await this.saveFile(loadConfig, config.configFile);169 config.program.secret = val;170}171exports.editScanInterval = async (val) => {172 const loadConfig = await this.loadFile(config.configFile);173 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }174 loadConfig.scanOptions.scanInterval = val;175 await this.saveFile(loadConfig, config.configFile);176 config.program.scanOptions.scanInterval = val;177 // update timer178 dbQueue.resetScanInterval();179}180exports.editSaveInterval = async (val) => {181 const loadConfig = await this.loadFile(config.configFile);182 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }183 loadConfig.scanOptions.saveInterval = val;184 await this.saveFile(loadConfig, config.configFile);185 config.program.scanOptions.saveInterval = val;186}187exports.editSkipImg = async (val) => {188 const loadConfig = await this.loadFile(config.configFile);189 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }190 loadConfig.scanOptions.skipImg = val;191 await this.saveFile(loadConfig, config.configFile);192 config.program.scanOptions.skipImg = val;193}194exports.editPause = async (val) => {195 const loadConfig = await this.loadFile(config.configFile);196 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }197 loadConfig.scanOptions.pause = val;198 await this.saveFile(loadConfig, config.configFile);199 config.program.scanOptions.pause = val;200}201exports.editBootScanDelay = async (val) => {202 const loadConfig = await this.loadFile(config.configFile);203 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }204 loadConfig.scanOptions.bootScanDelay = val;205 await this.saveFile(loadConfig, config.configFile);206 config.program.scanOptions.bootScanDelay = val;207}208exports.editMaxConcurrentTasks = async (val) => {209 const loadConfig = await this.loadFile(config.configFile);210 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }211 loadConfig.scanOptions.maxConcurrentTasks = val;212 await this.saveFile(loadConfig, config.configFile);213 config.program.scanOptions.maxConcurrentTasks = val;214}215exports.editCompressImages = async (val) => {216 const loadConfig = await this.loadFile(config.configFile);217 if (!loadConfig.scanOptions) { loadConfig.scanOptions = {}; }218 loadConfig.scanOptions.compressImage = val;219 await this.saveFile(loadConfig, config.configFile);220 config.program.scanOptions.compressImage = val;221}222exports.editWriteLogs = async (val) => {223 const loadConfig = await this.loadFile(config.configFile);224 loadConfig.writeLogs = val;225 await this.saveFile(loadConfig, config.configFile);226 config.program.writeLogs = val;227 if (val === false) {228 logger.reset();229 } else {230 logger.addFileLogger(config.program.storage.logsDirectory);231 }232}233exports.enableTranscode = async (val) => {234 const loadConfig = await this.loadFile(config.configFile);235 if (!loadConfig.transcode) { loadConfig.transcode = {}; }236 loadConfig.transcode.enabled = val;237 await this.saveFile(loadConfig, config.configFile);238 config.program.transcode.enabled = val;239}240exports.editDefaultCodec = async (val) => {241 const loadConfig = await this.loadFile(config.configFile);242 if (!loadConfig.transcode) { loadConfig.transcode = {}; }243 loadConfig.transcode.defaultCodec = val;244 await this.saveFile(loadConfig, config.configFile);245 config.program.transcode.defaultCodec = val;246}247exports.editDefaultBitrate = async (val) => {248 const loadConfig = await this.loadFile(config.configFile);249 if (!loadConfig.transcode) { loadConfig.transcode = {}; }250 loadConfig.transcode.defaultBitrate = val;251 await this.saveFile(loadConfig, config.configFile);252 config.program.transcode.defaultBitrate = val;253}254exports.editDefaultAlgorithm = async (val) => {255 const loadConfig = await this.loadFile(config.configFile);256 if (!loadConfig.transcode) { loadConfig.transcode = {}; }257 loadConfig.transcode.algorithm = val;258 await this.saveFile(loadConfig, config.configFile);259 config.program.transcode.algorithm = val;260}261exports.lockAdminApi = async (val) => {262 const loadConfig = await this.loadFile(config.configFile);263 loadConfig.lockAdmin = val;264 await this.saveFile(loadConfig, config.configFile);265 config.program.lockAdmin = val;266}267exports.enableFederation = async (val) => {268 const loadConfig = await this.loadFile(config.configFile);269 loadConfig.federation.enabled = val;270 await this.saveFile(loadConfig, config.configFile);271 config.program.federation.enabled = val;272 syncthing.setup();273}274exports.removeSSL = async () => {275 const loadConfig = await this.loadFile(config.configFile);276 delete loadConfig.ssl;277 await this.saveFile(loadConfig, config.configFile);278 delete config.program.ssl;279 mStreamServer.reboot();280}281function testSSL(jsonLoad) {282 return new Promise((resolve, reject) => {283 child.fork(path.join(__dirname, './ssl-test.js'), [JSON.stringify(jsonLoad)], { silent: true }).on('close', (code) => {284 if (code !== 0) {285 return reject('SSL Failure');286 }287 resolve();288 });289 });290}291exports.setSSL = async (cert, key) => {292 const sslObj = { key, cert };293 await testSSL(sslObj);294 const loadConfig = await this.loadFile(config.configFile);295 loadConfig.ssl = sslObj;296 await this.saveFile(loadConfig, config.configFile);297 298 config.program.ssl = sslObj;299 mStreamServer.reboot();...
load-config.test.js
Source:load-config.test.js
...13 sandbox.restore()14 })15 it('should use loadConfig.read to determine the appropriate values for required keys', () => {16 loadConfig.read.callsFake((overrideObject, key) => key)17 assert.deepEqual(loadConfig({}), {18 ethereum: {19 rpc: {20 address: 'ethereum.rpc.address',21 port: 'ethereum.rpc.port'22 },23 ws: {24 address: 'ethereum.ws.address',25 port: 'ethereum.ws.port'26 },27 infura: {28 id: 'ethereum.infura.id',29 secret: 'ethereum.infura.secret',30 network: 'ethereum.infura.network'31 },...
config-loading.js
Source:config-loading.js
...66 });67 describe("config file", () => {68 it("should load and cache the config with plugins and presets", () => {69 const opts = makeOpts();70 const options1 = loadConfig(opts).options;71 expect(options1.plugins.map(p => p.key)).toEqual([72 "plugin1",73 "plugin2",74 "plugin6",75 "plugin5",76 "plugin4",77 "plugin3",78 ]);79 const options2 = loadConfig(opts).options;80 expect(options2.plugins.length).toBe(options1.plugins.length);81 for (let i = 0; i < options2.plugins.length; i++) {82 expect(options2.plugins[i]).toBe(options1.plugins[i]);83 }84 });85 it("should load and cache the config for unique opts objects", () => {86 const options1 = loadConfig(makeOpts(true)).options;87 expect(options1.plugins.map(p => p.key)).toEqual([88 "plugin1",89 "plugin2",90 "plugin4",91 "plugin3",92 ]);93 const options2 = loadConfig(makeOpts(true)).options;94 expect(options2.plugins.length).toBe(options1.plugins.length);95 for (let i = 0; i < options2.plugins.length; i++) {96 expect(options2.plugins[i]).toBe(options1.plugins[i]);97 }98 });99 it("should invalidate config file plugins", () => {100 const opts = makeOpts();101 const options1 = loadConfig(opts).options;102 process.env.INVALIDATE_PLUGIN1 = true;103 const options2 = loadConfig(opts).options;104 expect(options2.plugins.length).toBe(options1.plugins.length);105 for (let i = 0; i < options1.plugins.length; i++) {106 if (i === 0) {107 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);108 } else {109 expect(options2.plugins[i]).toBe(options1.plugins[i]);110 }111 }112 process.env.INVALIDATE_PLUGIN3 = true;113 const options3 = loadConfig(opts).options;114 expect(options3.plugins.length).toBe(options1.plugins.length);115 for (let i = 0; i < options1.plugins.length; i++) {116 if (i === 0 || i === 5) {117 expect(options3.plugins[i]).not.toBe(options1.plugins[i]);118 } else {119 expect(options3.plugins[i]).toBe(options1.plugins[i]);120 }121 }122 });123 it("should invalidate config file presets and their children", () => {124 const opts = makeOpts();125 const options1 = loadConfig(opts).options;126 process.env.INVALIDATE_PRESET1 = true;127 const options2 = loadConfig(opts).options;128 expect(options2.plugins.length).toBe(options1.plugins.length);129 for (let i = 0; i < options1.plugins.length; i++) {130 if (i === 5) {131 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);132 } else {133 expect(options2.plugins[i]).toBe(options1.plugins[i]);134 }135 }136 process.env.INVALIDATE_PRESET2 = true;137 const options3 = loadConfig(opts).options;138 expect(options3.plugins.length).toBe(options1.plugins.length);139 for (let i = 0; i < options1.plugins.length; i++) {140 if (i === 4 || i === 5) {141 expect(options3.plugins[i]).not.toBe(options1.plugins[i]);142 } else {143 expect(options3.plugins[i]).toBe(options1.plugins[i]);144 }145 }146 });147 it("should invalidate the config file and its plugins/presets", () => {148 const opts = makeOpts();149 const options1 = loadConfig(opts).options;150 process.env.INVALIDATE_BABELRC = true;151 const options2 = loadConfig(opts).options;152 expect(options2.plugins.length).toBe(options1.plugins.length);153 for (let i = 0; i < options1.plugins.length; i++) {154 if (i === 0 || i === 1 || i === 4 || i === 5 || i === 6) {155 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);156 } else {157 expect(options2.plugins[i]).toBe(options1.plugins[i]);158 }159 }160 });161 });162 describe("programmatic plugins/presets", () => {163 it("should not invalidate the plugins when given a fresh object", () => {164 const opts = makeOpts();165 const options1 = loadConfig(opts).options;166 const options2 = loadConfig(Object.assign({}, opts)).options;167 expect(options2.plugins.length).toBe(options1.plugins.length);168 for (let i = 0; i < options2.plugins.length; i++) {169 expect(options2.plugins[i]).toBe(options1.plugins[i]);170 }171 });172 it("should not invalidate the plugins when given a fresh arrays", () => {173 const opts = makeOpts();174 const options1 = loadConfig(opts).options;175 const options2 = loadConfig({176 ...opts,177 plugins: opts.plugins.slice(),178 }).options;179 expect(options2.plugins.length).toBe(options1.plugins.length);180 for (let i = 0; i < options2.plugins.length; i++) {181 expect(options2.plugins[i]).toBe(options1.plugins[i]);182 }183 });184 it("should not invalidate the presets when given a fresh arrays", () => {185 const opts = makeOpts();186 const options1 = loadConfig(opts).options;187 const options2 = loadConfig({188 ...opts,189 presets: opts.presets.slice(),190 }).options;191 expect(options2.plugins.length).toBe(options1.plugins.length);192 for (let i = 0; i < options2.plugins.length; i++) {193 expect(options2.plugins[i]).toBe(options1.plugins[i]);194 }195 });196 it("should invalidate the plugins when given a fresh options", () => {197 const opts = makeOpts();198 const options1 = loadConfig(opts).options;199 const options2 = loadConfig({200 ...opts,201 plugins: opts.plugins.map(([plg, opt]) => [plg, { ...opt }]),202 }).options;203 expect(options2.plugins.length).toBe(options1.plugins.length);204 for (let i = 0; i < options2.plugins.length; i++) {205 if (i === 2) {206 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);207 } else {208 expect(options2.plugins[i]).toBe(options1.plugins[i]);209 }210 }211 });212 it("should invalidate the presets when given a fresh options", () => {213 const opts = makeOpts();214 const options1 = loadConfig(opts).options;215 const options2 = loadConfig({216 ...opts,217 presets: opts.presets.map(([plg, opt]) => [plg, { ...opt }]),218 }).options;219 expect(options2.plugins.length).toBe(options1.plugins.length);220 for (let i = 0; i < options2.plugins.length; i++) {221 if (i === 3) {222 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);223 } else {224 expect(options2.plugins[i]).toBe(options1.plugins[i]);225 }226 }227 });228 it("should invalidate the programmatic plugins", () => {229 const opts = makeOpts();230 const options1 = loadConfig(opts).options;231 process.env.INVALIDATE_PLUGIN6 = true;232 const options2 = loadConfig(opts).options;233 expect(options2.plugins.length).toBe(options1.plugins.length);234 for (let i = 0; i < options1.plugins.length; i++) {235 if (i === 2) {236 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);237 } else {238 expect(options2.plugins[i]).toBe(options1.plugins[i]);239 }240 }241 });242 it("should invalidate the programmatic presets and their children", () => {243 const opts = makeOpts();244 const options1 = loadConfig(opts).options;245 process.env.INVALIDATE_PRESET3 = true;246 const options2 = loadConfig(opts).options;247 expect(options2.plugins.length).toBe(options1.plugins.length);248 for (let i = 0; i < options1.plugins.length; i++) {249 if (i === 3) {250 expect(options2.plugins[i]).not.toBe(options1.plugins[i]);251 } else {252 expect(options2.plugins[i]).toBe(options1.plugins[i]);253 }254 }255 });256 it("should thrown when plugin is not valid", () => {257 const fooPlugin = {258 inherits: "inhertis-should-not-be-string",259 };260 const opts = {261 cwd: path.dirname(FILEPATH),262 filename: FILEPATH,263 plugins: [fooPlugin],264 };265 expect(() => loadConfig(opts)).toThrow(266 /\.inherits must be a function, or undefined/,267 );268 });269 });270 describe("caller metadata", () => {271 it("should pass caller data through", () => {272 const options1 = loadConfig({273 ...makeOpts(),274 caller: {275 name: "babel-test",276 someFlag: true,277 },278 }).options;279 expect(options1.caller.name).toBe("babel-test");280 expect(options1.caller.someFlag).toBe(true);281 });282 it("should pass unknown caller data through", () => {283 const options1 = loadConfig({284 ...makeOpts(),285 caller: undefined,286 }).options;287 expect(options1.caller).toBeUndefined();288 });289 it("should pass caller data to test functions", () => {290 const options1 = loadConfig({291 ...makeOpts(),292 caller: {293 name: "babel-test",294 someFlag: true,295 },296 overrides: [297 {298 test: (filename, { caller }) => caller.name === "babel-test",299 comments: false,300 },301 {302 test: (filename, { caller }) => caller.name !== "babel-test",303 ast: false,304 },...
AjaxLoading.js
Source:AjaxLoading.js
1/**2 * Created by jtrhb on 2016/3/15.3 */4//Ajax ÎÞÏÞ¼ÓÔØÎÄÕÂ5var loadConfig = {6 url_api:'http://localhost/plus/list.php',//·þÎñ¶Ë´¦Àí·¾¶7 typeid:0,//·ÖÀà8 page:{9 latestArticles:2,10 industryNews:2,11 view:2,12 deepInsight:2,13 etc:214 },//¿ªÊ¼Ò³Âë15 total:{16 latestArticles:2,17 industryNews:2,18 view:2,19 deepInsight:2,20 etc:221 },//×ÜÎÄÕÂÊý22 arr:{23 latestArticles:[],24 industryNews:[],25 view:[],26 deepInsight:[],27 etc:[]28 },//ÎÄÕÂÄÚÈÝArray29 pagesize: 15,//·ÖÒ³Êý30 loading : {31 latestArticles:0,32 industryNews:0,33 view:0,34 deepInsight:0,35 etc:036 },//¼ÓÔØ״̬,ĬÈÏΪδ¼ÓÔØ37 loaded : {38 latestArticles:0,39 industryNews:0,40 view:0,41 deepInsight:0,42 etc:043 }44};45function loadMoreApply(){46 var articletype = $('#myTab').children('.active').children('a').attr('href');47 articletype = articletype.substr(1);48 //Èç¹ûδ¼ÓÔØÊý¾Ý£¬¾Í¼ÓÔØ49 if(loadConfig.loading[articletype] == 0 && loadConfig.loaded[articletype] == 0){50 var typeid = loadConfig.typeid;51 var page = loadConfig.page[articletype];52 var pagesize = loadConfig.pagesize;53 var url = loadConfig.url_api;54 var data={ajax:'pullload',typeid:typeid,page:page,pagesize:pagesize,articletype:articletype};55 var sTop = document.body.scrollTop || document.documentElement.scrollTop, dHeight = $(document).height(), cHeight = document.documentElement.clientHeight;56//µ±¹ö¶¯Ìõ¸ß¶È¼ÓÉÏä¯ÀÀÆ÷¿ÉÊÓÇøÓò¸ß¶È´óÓÚµÈÓÚÎĵµ¸ß¶È¼õÈ¥ä¯ÀÀÆ÷¿ÉÊÓÇøÓò¸ß¶Èʱ£¬¾Í¼ÓÔØ¡£Îĵµ¸ß¶È¼õÈ¥ä¯ÀÀÆ÷¿ÉÊÓÇøÓò¸ß¶È£¬¾ÍÊÇ¿ÉÒÔ¹ö¶¯Ìõ¿ÉÒÔ¹ö¶¯µÄ¸ß¶È57 if (sTop + cHeight >= dHeight - cHeight) {58 loadConfig.loading[articletype] = 1;//½«¼ÓÔØ״̬¸ÄΪÒѼÓÔØ59 function ajax(url, data) {60 $.ajax({url: url,data: data,async: false,type: 'GET',dataType: 'json',success: function(data) {61 addContent(data,articletype);62 }});63 }64 ajax(url,data);65 }66 }67}68function addContent (rs,articletype){69 if(rs.statu== 1){70 var data = rs.list;71 var total = rs.total;72 loadConfig.load_num = rs.load_num;//¼ÓÔØ´ÎÊý£¬°´µÀÀíÓ¦¸ÃÔÚµÚÎå²½¾ÍÒѾ»ñÈ¡µ½¼ÓÔØ´ÎÊýºÍÊý¾Ý×ÜÊýµÄ73 var attSpan='';74 var length = data.length;75 for(var i=0;i<length;i++){76 switch(data[i].articletype)77 {78 case "industryNews":79 attSpan='<span class="articletype arc-type-in">²úÒµÐÂÎÅ</span>';80 break;81 case "view":82 attSpan='<span class="articletype arc-type-v">¹Ûµã</span>';83 break;84 case "deepInsight":85 attSpan='<span class="articletype arc-type-di">Éî¶È²âÆÀ</span>';86 break;87 case "etc":88 attSpan='<span class="articletype arc-type-etc">ÆäËû</span>';89 break;90 }91 loadConfig.arr[articletype].push('<div class="clearfix article-box ">');92 loadConfig.arr[articletype].push(attSpan);93 loadConfig.arr[articletype].push('<a href="'+data[i].arcurl+'" class="a-img" target="_blank"><img src="'+data[i].picname+'" width="220" height="146"/></a>');94 loadConfig.arr[articletype].push('<div class="article-box-ctt">');95 loadConfig.arr[articletype].push('<h4><a href="'+data[i].arcurl+'" target="_blank">'+data[i].fulltitle+'</a></h4>');96 loadConfig.arr[articletype].push('<div class="box-other">');97 loadConfig.arr[articletype].push('<span class="source-quote">'+data[i].writer+'</span>');98 loadConfig.arr[articletype].push('<time>'+data[i].stime+'</time></div>');//GetDateTimeMK(@me)99 loadConfig.arr[articletype].push('<div class="article-summary">'+data[i].description+'</div>');100 loadConfig.arr[articletype].push('<p class="tags-box">'+data[i].tagsById+'<i class="i-icon-bottom"></i></p></div>');//function=GetTags(@me)101 loadConfig.arr[articletype].push('<div class="idx-hldj"><div class="article-icon"><span class="comment-box"><i class="icon-comment"></i>');102 loadConfig.arr[articletype].push('<a href="'+data[i].arcurl+'" target="_blank">');103 //arr.push('<script src="/plus/pls.php?aid='+data[i].id+'" language="javascript"></script></a></span></div></div></div>');104 loadConfig.arr[articletype].push('</a></span></div></div></div>');105 }106 //var appendArticles = loadConfig.arr[articletype].join('');107 //var tabSelector = '#'+articletype+' div:first';108 //$(tabSelector).append(appendArticles);//JqueryÑ¡ÔñÒª¼ÓÔصÄDIV109 if(total<loadConfig.page[articletype]*loadConfig.pagesize || loadConfig.page[articletype] > loadConfig.load_num){110//Èç¹ûµ±Ç°Ò³Âë´óÓÚ¼ÓÔصÄ×Ü´ÎÊý111 loadConfig.loaded[articletype] = 1;112 var flagForRemoveListner = 1;113 for(var name in loadConfig.loaded){114 flagForRemoveListner = flagForRemoveListner && loadConfig.loaded[name];115 }116 if(flagForRemoveListner == 1){117 window.removeEventListener('srcoll',loadMoreApply,false);118 }119 }120 //loadConfig.page[articletype]++;//µÝÔöÒ³Âë121 }122 //loadConfig.loading = 0;//¼ÓÔØÍê±Ïºó£¬°Ñ¼ÓÔØ״̬¸ÄΪ0123 /*124 else{125 var lmSelector = '#'+articletype+' div.idx-more';126 $(lmSelector).remove();127 }128 */129}130function loadDataToDom(){131 var articletype = $('#myTab').children('.active').children('a').attr('href');132 articletype = articletype.substr(1);133 var appendArticles = loadConfig.arr[articletype].join('');134 var tabSelector = '#'+articletype+' div:first';135 $(tabSelector).append(appendArticles);//JqueryÑ¡ÔñÒª¼ÓÔصÄDIV136 if(loadConfig.loaded[articletype]){137 var lmSelector = '#'+articletype+' div.idx-more';138 $(lmSelector).remove();139 }140 appendArticles = '';141 loadConfig.arr[articletype] = [];142 loadConfig.page[articletype]++;//µÝÔöÒ³Âë143 loadConfig.loading[articletype] = 0;//¼ÓÔØÍê±Ïºó£¬°Ñ¼ÓÔØ״̬¸ÄΪ0144}145function pullLoad(){146 window.addEventListener('scroll', loadMoreApply, false);147}...
config.unit.test.js
Source:config.unit.test.js
...5const pathToConfig = join(__dirname, '_resolvedata', 'without-function')6const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function')7describe('config', () => {8 it('Should get the configuration', async () => {9 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)10 expect(config.customConfig).toBe(true)11 })12 it('Should pass the phase correctly', async () => {13 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)14 expect(config.phase).toBe(PHASE_DEVELOPMENT_SERVER)15 })16 it('Should pass the defaultConfig correctly', async () => {17 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)18 expect(config.defaultConfig).toBeDefined()19 })20 it('Should assign object defaults deeply to user config', async () => {21 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)22 expect(config.distDir).toEqual('.next')23 expect(config.onDemandEntries.maxInactiveAge).toBeDefined()24 })25 it('Should pass the customConfig correctly', async () => {26 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {27 customConfig: true,28 })29 expect(config.customConfig).toBe(true)30 })31 it('Should not pass the customConfig when it is null', async () => {32 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)33 expect(config.webpack).toBe(null)34 })35 it('Should assign object defaults deeply to customConfig', async () => {36 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {37 customConfig: true,38 onDemandEntries: { custom: true },39 })40 expect(config.customConfig).toBe(true)41 expect(config.onDemandEntries.maxInactiveAge).toBeDefined()42 })43 it('Should allow setting objects which do not have defaults', async () => {44 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {45 bogusSetting: { custom: true },46 })47 expect(config.bogusSetting).toBeDefined()48 expect(config.bogusSetting.custom).toBe(true)49 })50 it('Should override defaults for arrays from user arrays', async () => {51 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {52 pageExtensions: ['.bogus'],53 })54 expect(config.pageExtensions).toEqual(['.bogus'])55 })56 it('Should throw when an invalid target is provided', async () => {57 await expect(async () => {58 await loadConfig(59 PHASE_DEVELOPMENT_SERVER,60 join(__dirname, '_resolvedata', 'invalid-target')61 )62 }).rejects.toThrow(/Specified target is invalid/)63 })64 it('Should pass when a valid target is provided', async () => {65 const config = await loadConfig(66 PHASE_DEVELOPMENT_SERVER,67 join(__dirname, '_resolvedata', 'valid-target')68 )69 expect(config.target).toBe('serverless')70 })71 it('Should throw an error when next.config.js is not present', async () => {72 await expect(73 async () =>74 await loadConfig(75 PHASE_DEVELOPMENT_SERVER,76 join(__dirname, '_resolvedata', 'typescript-config')77 )78 ).rejects.toThrow(79 /Configuring Next.js via .+ is not supported. Please replace the file with 'next.config.js'/80 )81 })82 it('Should not throw an error when two versions of next.config.js are present', async () => {83 const config = await loadConfig(84 PHASE_DEVELOPMENT_SERVER,85 join(__dirname, '_resolvedata', 'js-ts-config')86 )87 expect(config.__test__ext).toBe('js')88 })89 it('Should ignore configs set to `undefined`', async () => {90 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {91 target: undefined,92 })93 expect(config.target).toBe('server')94 })95 it('Should ignore configs set to `null`', async () => {96 const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {97 target: null,98 })99 expect(config.target).toBe('server')100 })...
config.test.js
Source:config.test.js
...5const pathToConfig = join(__dirname, '_resolvedata', 'without-function')6const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function')7describe('config', () => {8 it('Should get the configuration', () => {9 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)10 expect(config.customConfig).toBe(true)11 })12 it('Should pass the phase correctly', () => {13 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)14 expect(config.phase).toBe(PHASE_DEVELOPMENT_SERVER)15 })16 it('Should pass the defaultConfig correctly', () => {17 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)18 expect(config.defaultConfig).toBeDefined()19 })20 it('Should assign object defaults deeply to user config', () => {21 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)22 expect(config.distDir).toEqual('.next')23 expect(config.onDemandEntries.maxInactiveAge).toBeDefined()24 })25 it('Should pass the customConfig correctly', () => {26 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {27 customConfig: true28 })29 expect(config.customConfig).toBe(true)30 })31 it('Should not pass the customConfig when it is null', () => {32 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)33 expect(config.webpack).toBe(null)34 })35 it('Should assign object defaults deeply to customConfig', () => {36 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {37 customConfig: true,38 onDemandEntries: { custom: true }39 })40 expect(config.customConfig).toBe(true)41 expect(config.onDemandEntries.maxInactiveAge).toBeDefined()42 })43 it('Should allow setting objects which do not have defaults', () => {44 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {45 bogusSetting: { custom: true }46 })47 expect(config.bogusSetting).toBeDefined()48 expect(config.bogusSetting.custom).toBe(true)49 })50 it('Should override defaults for arrays from user arrays', () => {51 const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {52 pageExtensions: ['.bogus']53 })54 expect(config.pageExtensions).toEqual(['.bogus'])55 })56 it('Should throw when an invalid target is provided', () => {57 try {58 loadConfig(59 PHASE_DEVELOPMENT_SERVER,60 join(__dirname, '_resolvedata', 'invalid-target')61 )62 // makes sure we don't just pass if the loadConfig passes while it should fail63 throw new Error('failed')64 } catch (err) {65 expect(err.message).toMatch(/Specified target is invalid/)66 }67 })68 it('Should pass when a valid target is provided', () => {69 const config = loadConfig(70 PHASE_DEVELOPMENT_SERVER,71 join(__dirname, '_resolvedata', 'valid-target')72 )73 expect(config.target).toBe('serverless')74 })...
config-loader.js
Source:config-loader.js
...23 const error = t.throws(loadConfig.bind(loadConfig, 'test/fixtures/nodecg-core/cfg/invalidSSL.json'));24 t.is(error.message, 'ssl.keyPath: must be of type String\nssl.certificatePath: must be of type String');25});26test('should load defaults when the config file does not exist', t => {27 const result = loadConfig('');28 t.is(result.config.host, '0.0.0.0');29 t.is(result.config.port, 9090);30});31test('should not have any whitelisted nor blacklisted bundles by default', t => {32 const result = loadConfig('');33 t.is(result.config.bundles.enabled, null);34 t.is(result.config.bundles.disabled, null);...
loadConfig.test.js
Source:loadConfig.test.js
...7import { loadConfig } from '../lib/loadConfig'8describe('loadConfig', function () {9 it('should load json5 file', async function () {10 expect(11 await loadConfig('fixture/loadConfig/.filerc', { cwd: __dirname })12 ).toEqual({13 'name': 'fixture',14 'version': '0.0.1'15 })16 })17 it('should load json5 file 2', async function () {18 expect(19 await loadConfig('fixture/loadConfig/.jsonrc', { cwd: __dirname })20 ).toEqual({21 'name': 'fixture',22 'version': '0.0.1',23 x: ['222']24 })25 })26 it('should load js file', async function () {27 expect(28 await loadConfig('fixture/loadConfig/file.js', { cwd: __dirname })29 ).toEqual({30 'name': 'fixture',31 'version': '0.0.1'32 })33 })34 it('should throws error when js file is not found', async function () {35 try {36 await loadConfig('fixture/loadConfig/404.js', { cwd: __dirname })37 } catch (ex) {38 expect(ex).not.toBeNull()39 }40 })41 it('should throws error when json5 file is not found', async function () {42 try {43 await loadConfig('fixture/loadConfig/404.json', { cwd: __dirname })44 } catch (ex) {45 expect(ex).not.toBeNull()46 }47 })...
Using AI Code Generation
1import { loadConfig } from 'storybook-root-config';2import { configure } from '@storybook/react';3import '../src/index.css';4const loadStories = () => {5 const req = require.context('../src', true, /\.stories\.js$/);6 req.keys().forEach(filename => req(filename));7};8const config = loadConfig(__dirname);9configure(loadStories, config);
Using AI Code Generation
1const { loadConfig } = require('storybook-root-config');2const { config } = loadConfig(__dirname);3module.exports = config;4const path = require('path');5const { config } = require('test.js');6module.exports = {7 stories: [path.resolve(__dirname, '../src/**/*.stories.tsx')],8};9const { loadConfig } = require('storybook-root-config');10const { config } = loadConfig(__dirname);11module.exports = config;12const { loadConfig } = require('storybook-root-config');13const { config } = loadConfig(__dirname);14module.exports = config;15const { loadConfig } = require('storybook-root-config');16const { config } = loadConfig(__dirname);17module.exports = config;18const { loadConfig } = require('storybook-root-config');19const { config } = loadConfig(__dirname);20module.exports = config;21const { loadConfig } = require('storybook-root-config');22const { config } = loadConfig(__dirname);23module.exports = config;24const path = require('path');25const { config } = require('test.js');26module.exports = {27 stories: [path.resolve(__dirname, '../src/**/*.stories.tsx')],28};
Using AI Code Generation
1const config = loadConfig({2 configDir: path.resolve(__dirname, '../.storybook'),3});4module.exports = {5};6"scripts": {7 }8import { addDecorator, addParameters } from '@storybook/react';9import { withA11y } from '@storybook/addon-a11y';10import { withKnobs } from '@storybook/addon-knobs';11import { withNextRouter } from 'storybook-addon-next-router';12import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';13addDecorator(withNextRouter());14addDecorator(withKnobs());15addDecorator(withA11y);16addParameters({17 viewport: {18 },19});20import React from 'react';21import { Button } from '../components/Button';22export default {23};24const Template = (args) => <Button {...args} />;
Using AI Code Generation
1const { loadConfig } = require('@storybook/core/server');2const config = loadConfig({ configDir: path.resolve(__dirname, '../.storybook') });3const { loadCustomAddons } = require('@storybook/core/server');4const customAddons = loadCustomAddons(config);5const { loadCustomPresets } = require('@storybook/core/server');6const customPresets = loadCustomPresets(config);7const { loadCustomPreviewEntries } = require('@storybook/core/server');8const customPreviewEntries = loadCustomPreviewEntries(config);9const { loadCustomManagerEntries } = require('@storybook/core/server');10const customManagerEntries = loadCustomManagerEntries(config);11const { loadCustomBabelConfig } = require('@storybook/core/server');12const customBabelConfig = loadCustomBabelConfig(config);13const { loadCustomWebpackConfig } = require('@storybook/core/server');14const customWebpackConfig = loadCustomWebpackConfig(config);15const { loadCustomPreviewHeadHtml } = require('@storybook/core/server');16const customPreviewHeadHtml = loadCustomPreviewHeadHtml(config);17const { loadCustomManagerHeadHtml } = require('@storybook/core/server');18const customManagerHeadHtml = loadCustomManagerHeadHtml(config);19const { loadCustomPreviewBodyHtml } = require('@storybook/core/server');20const customPreviewBodyHtml = loadCustomPreviewBodyHtml(config);21const { loadCustomManagerBodyHtml } = require('@storybook/core/server');22const customManagerBodyHtml = loadCustomManagerBodyHtml(config);23const { loadCustomManagerWebpackConfig } = require('@storybook/core/server');24const customManagerWebpackConfig = loadCustomManagerWebpackConfig(config);
Using AI Code Generation
1const { loadConfig } = require('@storybook/core/server');2const config = loadConfig({ configDir: './storybook' });3module.exports = config;4const { loadConfig } = require('@storybook/react/server');5const config = loadConfig({ configDir: './storybook' });6module.exports = config;7const { loadConfig } = require('@storybook/vue/server');8const config = loadConfig({ configDir: './storybook' });9module.exports = config;10const { loadConfig } = require('@storybook/angular/server');11const config = loadConfig({ configDir: './storybook' });12module.exports = config;13const { loadConfig } = require('@storybook/web-components/server');14const config = loadConfig({ configDir: './storybook' });15module.exports = config;16const { loadConfig } = require('@storybook/svelte/server');17const config = loadConfig({ configDir: './storybook' });18module.exports = config;19const { loadConfig } = require('@storybook/riot/server');20const config = loadConfig({ configDir: './storybook' });21module.exports = config;22const { loadConfig } = require('@storybook/preact/server');23const config = loadConfig({ configDir: './storybook' });24module.exports = config;25const { loadConfig } = require('@storybook/marko/server');26const config = loadConfig({ configDir: './storybook' });27module.exports = config;28const { loadConfig } = require('@storybook/mithril/server');29const config = loadConfig({ configDir: './storybook' });30module.exports = config;31const { loadConfig } = require('@storybook/marionette/server');32const config = loadConfig({ configDir: './storybook' });33module.exports = config;34const { loadConfig } = require('@storybook/mithril/server');
Using AI Code Generation
1const { loadConfig } = require('@storybook/core/server');2const rootConfig = loadConfig({ configDir: './.storybook' });3const { config } = rootConfig;4const { loadConfig } = require('@storybook/core/server');5const coreConfig = loadConfig({ configDir: './.storybook' });6const { config } = coreConfig;7const { loadConfig } = require('@storybook/react/server');8const reactConfig = loadConfig({ configDir: './.storybook' });9const { config } = reactConfig;10const { loadConfig } = require('@storybook/vue/server');11const vueConfig = loadConfig({ configDir: './.storybook' });12const { config } = vueConfig;13const { loadConfig } = require('@storybook/angular/server');14const angularConfig = loadConfig({ configDir: './.storybook' });15const { config } = angularConfig;16const { loadConfig } = require('@storybook/html/server');17const htmlConfig = loadConfig({ configDir: './.storybook' });18const { config } = htmlConfig;19const { loadConfig } = require('@storybook/svelte/server');20const svelteConfig = loadConfig({ configDir: './.storybook' });21const { config } = svelteConfig;22const { loadConfig } = require('@storybook/marko/server');23const markoConfig = loadConfig({ configDir: './.storybook' });24const { config } = markoConfig;25const { loadConfig } = require('@storybook/mithril/server');26const mithrilConfig = loadConfig({ configDir: './.storybook' });27const { config } = mithrilConfig;28const { loadConfig } = require('@storybook/riot/server');29const riotConfig = loadConfig({ configDir: './.storybook' });30const { config } = riotConfig;31const { loadConfig } = require('@
Using AI Code Generation
1const { loadConfig } = require('@storybook/core/server');2const config = loadConfig({3 configDir: path.resolve(__dirname, '../.storybook'),4 corePresets: [require.resolve('@storybook/core/dist/server/common/presets.js')],5 babelOptions: {},6 typescriptOptions: {},7 features: {},8 refs: {},9 frameworkOptions: {},
Using AI Code Generation
1const { loadConfig } = require('storybook-root-config');2const config = loadConfig(__dirname, {3 presets: [require.resolve('storybook-addon-root-attribute/register')],4});5module.exports = config;6module.exports = {7};8export const parameters = {9 actions: { argTypesRegex: '^on[A-Z].*' },10};11 html[root='root'] {12 font-size: 16px;13 line-height: 1.5;14 font-family: 'Open Sans', sans-serif;15 font-weight: 400;16 color: #000000;17 }18const path = require('path');19module.exports = ({ config }) => {20 config.resolve.alias = {21 '@storybook/addon-knobs': path.resolve(__dirname, '../src'),22 };23 config.module.rules.push({24 {25 options: {26 sassOptions: {27 includePaths: [path.resolve(__dirname, '../src/styles')],28 },29 },30 },31 });32 return config;33};34"scripts": {35},36"devDependencies": {
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!!