How to use validateConfig method in root

Best JavaScript code snippet using root

settings.js

Source:settings.js Github

copy

Full Screen

1class Settings {2 constructor() {3 if (!localStorage) alert('Hmm, looks like you browser doesnt support localStorage!')4 this.validateConfig();5 };6 get deafultSettings() {7 return {8 "gameSize":50,9 "gameSpeed":65,10 "startLength":3,11 "head":"/static/img/gameAssets/Deafult/head.png",12 "tail":"/static/img/gameAssets/Deafult/tail.png",13 "corner":"/static/img/gameAssets/Deafult/corner.png",14 "straight":"/static/img/gameAssets/Deafult/straight.png",15 "food":"/static/img/gameAssets/Deafult/food.png",16 "background":"/static/img/gameAssets/Deafult/background.png",17 "up":87,18 "down":83,19 "left":65,20 "right":68,21 "upKey":"w",22 "downKey":"s",23 "leftKey":"a",24 "rightKey":"d"25 };26 };27 get imageSizes() {28 return {29 head: [60, 60],30 tail: [60, 60],31 corner: [60, 60],32 straight: [60, 60],33 food: [60, 60],34 background: [1000, 1000]35 };36 };37 validateConfig() {38 let settings = this.deafultSettings;39 let config = {};40 if (localStorage.config) {41 try {42 config = JSON.parse(localStorage.config);43 }44 catch (err) {45 localStorage.config = '{}';46 };47 for (const setting of Object.keys(settings)) {48 if (!(setting in config)) {49 config[setting] = settings[setting];50 };51 };52 let imgs = {};53 ['head', 'tail', 'corner', 'straight', 'food'].forEach((el) => {54 imgs[el] = new Image();55 imgs[el].src = config[el];56 imgs[el].onerror = () => {57 this.reset();58 location.reload();59 };60 imgs[el].onload = () => {61 if (imgs[el].width != this.imageSizes[el][0] && imgs[el].height != this.imageSizes[el][1]) {62 this.reset();63 location.reload();64 };65 };66 });67 imgs.background = new Image();68 imgs.background.src = config.background;69 imgs.background.onerror = () => {70 this.reset();71 location.reload();72 };73 imgs.background.onload = () => {74 if (imgs.background.width != this.imageSizes.background[0] && imgs.background.height != this.imageSizes.background[1]) {75 this.reset();76 location.reload();77 };78 };79 }80 else {81 config = settings;82 };83 localStorage.config = JSON.stringify(config);84 return {85 };86 };87 reset() {88 localStorage.config = undefined;89 this.validateConfig();90 }91 toJSON() {92 return JSON.parse(localStorage.config);93 };94 95 96 get gameSize() {97 try {98 if (localStorage.config) {99 return JSON.parse(localStorage.config).gameSize ? JSON.parse(localStorage.config).gameSize : (() => {100 this.validateConfig();101 return this.deafultSettings.gameSize;102 })();103 };104 }105 catch(err) {106 this.validateConfig();107 return this.deafultSettings.gameSize;108 };109 };110 set gameSize(value) {111 if (!Number.isInteger(parseInt(value))) return;112 try {113 if (localStorage.config) {114 let settings = JSON.parse(localStorage.config);115 settings.gameSize = value;116 return localStorage.config = JSON.stringify(settings);117 };118 }119 catch(err) {120 this.validateConfig();121 return this.deafultSettings.gameSize;122 };123 };124 get gameSpeed() {125 try {126 if (localStorage.config) {127 return JSON.parse(localStorage.config).gameSpeed ? JSON.parse(localStorage.config).gameSpeed : (() => {128 this.validateConfig();129 return this.deafultSettings.gameSpeed;130 })();131 };132 }133 catch(err) {134 this.validateConfig();135 return this.deafultSettings.gameSpeed;136 };137 };138 set gameSpeed(value) {139 if (!Number.isInteger(parseInt(value))) return;140 try {141 if (localStorage.config) {142 let settings = JSON.parse(localStorage.config);143 settings.gameSpeed = value;144 return localStorage.config = JSON.stringify(settings);145 };146 }147 catch(err) {148 this.validateConfig();149 return this.deafultSettings.gameSpeed;150 };151 };152 get startLength() {153 try {154 if (localStorage.config) {155 return JSON.parse(localStorage.config).startLength ? JSON.parse(localStorage.config).startLength : (() => {156 this.validateConfig();157 return this.deafultSettings.startLength;158 })();159 };160 }161 catch(err) {162 this.validateConfig();163 return this.deafultSettings.startLength;164 };165 };166 set startLength(value) {167 if (!Number.isInteger(parseInt(value))) return;168 try {169 if (localStorage.config) {170 let settings = JSON.parse(localStorage.config);171 settings.startLength = value;172 return localStorage.config = JSON.stringify(settings);173 };174 }175 catch(err) {176 this.validateConfig();177 return this.deafultSettings.startLength;178 };179 };180 get head() {181 try {182 if (localStorage.config) {183 return JSON.parse(localStorage.config).head ? JSON.parse(localStorage.config).head : (() => {184 this.validateConfig();185 return this.deafultSettings.head;186 })();187 };188 }189 catch(err) {190 this.validateConfig();191 return this.deafultSettings.head;192 };193 };194 set head(value) {195 try {196 if (localStorage.config) {197 let settings = JSON.parse(localStorage.config);198 let img = new Image();199 img.src = value;200 201 img.onerror = () => {202 this.reset();203 location.reload();204 };205 img.onload = () => {206 if (img.width != this.imageSizes.head[0] && img.height != this.imageSizes.head[1]) {207 this.reset();208 location.reload();209 };210 };211 settings.head = value;212 return localStorage.config = JSON.stringify(settings);213 };214 }215 catch(err) {216 this.validateConfig();217 return this.deafultSettings.head;218 };219 };220 get tail() {221 try {222 if (localStorage.config) {223 return JSON.parse(localStorage.config).tail ? JSON.parse(localStorage.config).tail : (() => {224 this.validateConfig();225 return this.deafultSettings.tail;226 })();227 };228 }229 catch(err) {230 this.validateConfig();231 return this.deafultSettings.tail;232 };233 };234 set tail(value) {235 try {236 if (localStorage.config) {237 let settings = JSON.parse(localStorage.config);238 let img = new Image();239 img.src = value;240 241 img.onerror = () => {242 this.reset();243 location.reload();244 };245 img.onload = () => {246 if (img.width != this.imageSizes.tail[0] && img.height != this.imageSizes.tail[1]) {247 this.reset();248 location.reload();249 };250 };251 settings.tail = value;252 return localStorage.config = JSON.stringify(settings);253 };254 }255 catch(err) {256 this.validateConfig();257 return this.deafultSettings.tail;258 };259 };260 get corner() {261 try {262 if (localStorage.config) {263 return JSON.parse(localStorage.config).corner ? JSON.parse(localStorage.config).corner : (() => {264 this.validateConfig();265 return this.deafultSettings.corner;266 })();267 };268 }269 catch(err) {270 this.validateConfig();271 return this.deafultSettings.corner;272 };273 };274 set corner(value) {275 try {276 if (localStorage.config) {277 let settings = JSON.parse(localStorage.config);278 let img = new Image();279 img.src = value;280 281 img.onerror = () => {282 this.reset();283 location.reload();284 };285 img.onload = () => {286 if (img.width != this.imageSizes.corner[0] && img.height != this.imageSizes.corner[1]) {287 this.reset();288 location.reload();289 };290 };291 settings.corner = value;292 return localStorage.config = JSON.stringify(settings);293 };294 }295 catch(err) {296 this.validateConfig();297 return this.deafultSettings.corner;298 };299 };300 get straight() {301 try {302 if (localStorage.config) {303 return JSON.parse(localStorage.config).straight ? JSON.parse(localStorage.config).straight : (() => {304 this.validateConfig();305 return this.deafultSettings.straight;306 })();307 };308 }309 catch(err) {310 this.validateConfig();311 return this.deafultSettings.straight;312 };313 };314 set straight(value) {315 try {316 if (localStorage.config) {317 let settings = JSON.parse(localStorage.config);318 let img = new Image();319 img.src = value;320 321 img.onerror = () => {322 this.reset();323 location.reload();324 };325 img.onload = () => {326 if (img.width != this.imageSizes.straight[0] && img.height != this.imageSizes.straight[1]) {327 this.reset();328 location.reload();329 };330 };331 settings.straight = value;332 return localStorage.config = JSON.stringify(settings);333 };334 }335 catch(err) {336 this.validateConfig();337 return this.deafultSettings.straight;338 };339 };340 get food() {341 try {342 if (localStorage.config) {343 return JSON.parse(localStorage.config).food ? JSON.parse(localStorage.config).food : (() => {344 this.validateConfig();345 return this.deafultSettings.food;346 })();347 };348 }349 catch(err) {350 this.validateConfig();351 return this.deafultSettings.food;352 };353 };354 set food(value) {355 try {356 if (localStorage.config) {357 let settings = JSON.parse(localStorage.config);358 let img = new Image();359 img.src = value;360 361 img.onerror = () => {362 this.reset();363 location.reload();364 };365 img.onload = () => {366 if (img.width != this.imageSizes.food[0] && img.height != this.imageSizes.food[1]) {367 this.reset();368 location.reload();369 };370 };371 settings.food = value;372 return localStorage.config = JSON.stringify(settings);373 };374 }375 catch(err) {376 this.validateConfig();377 return this.deafultSettings.food;378 };379 };380 get background() {381 try {382 if (localStorage.config) {383 return JSON.parse(localStorage.config).background ? JSON.parse(localStorage.config).background : (() => {384 this.validateConfig();385 return this.deafultSettings.background;386 })();387 };388 }389 catch(err) {390 this.validateConfig();391 return this.deafultSettings.background;392 };393 };394 set background(value) {395 try {396 if (localStorage.config) {397 let settings = JSON.parse(localStorage.config);398 let img = new Image();399 img.src = value;400 401 img.onerror = () => {402 this.reset();403 location.reload();404 };405 img.onload = () => {406 if (img.width != this.imageSizes.background[0] && img.height != this.imageSizes.background[1]) {407 this.reset();408 location.reload();409 };410 };411 settings.background = value;412 return localStorage.config = JSON.stringify(settings);413 };414 }415 catch(err) {416 this.validateConfig();417 return this.deafultSettings.background;418 };419 };420 421 get up() {422 try {423 if (localStorage.config) {424 return JSON.parse(localStorage.config).up ? JSON.parse(localStorage.config).up : (() => {425 this.validateConfig();426 return this.deafultSettings.up;427 })();428 };429 }430 catch(err) {431 this.validateConfig();432 return this.deafultSettings.up;433 };434 };435 set up(value) {436 if (!Number.isInteger(parseInt(value))) return;437 try {438 if (localStorage.config) {439 let settings = JSON.parse(localStorage.config);440 settings.up = value;441 return localStorage.config = JSON.stringify(settings);442 };443 }444 catch(err) {445 this.validateConfig();446 return this.deafultSettings.up;447 };448 };449 450 get down() {451 try {452 if (localStorage.config) {453 return JSON.parse(localStorage.config).down ? JSON.parse(localStorage.config).down : (() => {454 this.validateConfig();455 return this.deafultSettings.down;456 })();457 };458 }459 catch(err) {460 this.validateConfig();461 return this.deafultSettings.down;462 };463 };464 set down(value) {465 if (!Number.isInteger(parseInt(value))) return;466 try {467 if (localStorage.config) {468 let settings = JSON.parse(localStorage.config);469 settings.down = value;470 return localStorage.config = JSON.stringify(settings);471 };472 }473 catch(err) {474 this.validateConfig();475 return this.deafultSettings.down;476 };477 };478 479 get left() {480 try {481 if (localStorage.config) {482 return JSON.parse(localStorage.config).left ? JSON.parse(localStorage.config).left : (() => {483 this.validateConfig();484 return this.deafultSettings.left;485 })();486 };487 }488 catch(err) {489 this.validateConfig();490 return this.deafultSettings.left;491 };492 };493 set left(value) {494 if (!Number.isInteger(parseInt(value))) return;495 try {496 if (localStorage.config) {497 let settings = JSON.parse(localStorage.config);498 settings.left = value;499 return localStorage.config = JSON.stringify(settings);500 };501 }502 catch(err) {503 this.validateConfig();504 return this.deafultSettings.left;505 };506 };507 508 get right() {509 try {510 if (localStorage.config) {511 return JSON.parse(localStorage.config).right ? JSON.parse(localStorage.config).right : (() => {512 this.validateConfig();513 return this.deafultSettings.right;514 })();515 };516 }517 catch(err) {518 this.validateConfig();519 return this.deafultSettings.right;520 };521 };522 set right(value) {523 if (!Number.isInteger(parseInt(value))) return;524 try {525 if (localStorage.config) {526 let settings = JSON.parse(localStorage.config);527 settings.right = value;528 return localStorage.config = JSON.stringify(settings);529 };530 }531 catch(err) {532 this.validateConfig();533 return this.deafultSettings.right;534 };535 };536 537 get upKey() {538 try {539 if (localStorage.config) {540 return JSON.parse(localStorage.config).upKey ? JSON.parse(localStorage.config).upKey : (() => {541 this.validateConfig();542 return this.deafultSettings.upKey;543 })();544 };545 }546 catch(err) {547 this.validateConfig();548 return this.deafultSettings.upKey;549 };550 };551 set upKey(value) {552 try {553 if (localStorage.config) {554 let settings = JSON.parse(localStorage.config);555 settings.upKey = value;556 return localStorage.config = JSON.stringify(settings);557 };558 }559 catch(err) {560 this.validateConfig();561 return this.deafultSettings.upKey;562 };563 };564 565 get downKey() {566 try {567 if (localStorage.config) {568 return JSON.parse(localStorage.config).downKey ? JSON.parse(localStorage.config).downKey : (() => {569 this.validateConfig();570 return this.deafultSettings.downKey;571 })();572 };573 }574 catch(err) {575 this.validateConfig();576 return this.deafultSettings.downKey;577 };578 };579 set downKey(value) {580 try {581 if (localStorage.config) {582 let settings = JSON.parse(localStorage.config);583 settings.downKey = value;584 return localStorage.config = JSON.stringify(settings);585 };586 }587 catch(err) {588 this.validateConfig();589 return this.deafultSettings.downKey;590 };591 };592 593 get leftKey() {594 try {595 if (localStorage.config) {596 return JSON.parse(localStorage.config).leftKey ? JSON.parse(localStorage.config).leftKey : (() => {597 this.validateConfig();598 return this.deafultSettings.leftKey;599 })();600 };601 }602 catch(err) {603 this.validateConfig();604 return this.deafultSettings.leftKey;605 };606 };607 set leftKey(value) {608 try {609 if (localStorage.config) {610 let settings = JSON.parse(localStorage.config);611 settings.leftKey = value;612 return localStorage.config = JSON.stringify(settings);613 };614 }615 catch(err) {616 this.validateConfig();617 return this.deafultSettings.leftKey;618 };619 };620 621 622 get rightKey() {623 try {624 if (localStorage.config) {625 return JSON.parse(localStorage.config).rightKey ? JSON.parse(localStorage.config).rightKey : (() => {626 this.validateConfig();627 return this.deafultSettings.rightKey;628 })();629 };630 }631 catch(err) {632 this.validateConfig();633 return this.deafultSettings.rightKey;634 };635 };636 set rightKey(value) {637 try {638 if (localStorage.config) {639 let settings = JSON.parse(localStorage.config);640 settings.rightKey = value;641 return localStorage.config = JSON.stringify(settings);642 };643 }644 catch(err) {645 this.validateConfig();646 return this.deafultSettings.rightKey;647 };648 };...

Full Screen

Full Screen

configSchema.spec.js

Source:configSchema.spec.js Github

copy

Full Screen

...26 ],27 };28 it('should not throw if no errors', () => {29 expect(() => {30 validateConfig(validConfig);31 }).not.toThrowError();32 });33 it('should throw if backend is not defined in config', () => {34 expect(() => {35 validateConfig({ foo: 'bar' });36 }).toThrowError("config should have required property 'backend'");37 });38 it('should throw if backend name is not defined in config', () => {39 expect(() => {40 validateConfig({ foo: 'bar', backend: {} });41 }).toThrowError("'backend' should have required property 'name'");42 });43 it('should throw if backend name is not a string in config', () => {44 expect(() => {45 validateConfig({ foo: 'bar', backend: { name: {} } });46 }).toThrowError("'backend.name' should be string");47 });48 it('should throw if backend.open_authoring is not a boolean in config', () => {49 expect(() => {50 validateConfig(merge(validConfig, { backend: { open_authoring: 'true' } }));51 }).toThrowError("'backend.open_authoring' should be boolean");52 });53 it('should not throw if backend.open_authoring is boolean in config', () => {54 expect(() => {55 validateConfig(merge(validConfig, { backend: { open_authoring: true } }));56 }).not.toThrowError();57 });58 it('should throw if backend.auth_scope is not "repo" or "public_repo" in config', () => {59 expect(() => {60 validateConfig(merge(validConfig, { backend: { auth_scope: 'user' } }));61 }).toThrowError("'backend.auth_scope' should be equal to one of the allowed values");62 });63 it('should not throw if backend.auth_scope is one of "repo" or "public_repo" in config', () => {64 expect(() => {65 validateConfig(merge(validConfig, { backend: { auth_scope: 'repo' } }));66 }).not.toThrowError();67 expect(() => {68 validateConfig(merge(validConfig, { backend: { auth_scope: 'public_repo' } }));69 }).not.toThrowError();70 });71 it('should throw if media_folder is not defined in config', () => {72 expect(() => {73 validateConfig({ foo: 'bar', backend: { name: 'bar' } });74 }).toThrowError("config should have required property 'media_folder'");75 });76 it('should throw if media_folder is not a string in config', () => {77 expect(() => {78 validateConfig({ foo: 'bar', backend: { name: 'bar' }, media_folder: {} });79 }).toThrowError("'media_folder' should be string");80 });81 it('should throw if collections is not defined in config', () => {82 expect(() => {83 validateConfig({ foo: 'bar', backend: { name: 'bar' }, media_folder: 'baz' });84 }).toThrowError("config should have required property 'collections'");85 });86 it('should throw if collections not an array in config', () => {87 expect(() => {88 validateConfig({89 foo: 'bar',90 backend: { name: 'bar' },91 media_folder: 'baz',92 collections: {},93 });94 }).toThrowError("'collections' should be array");95 });96 it('should throw if collections is an empty array in config', () => {97 expect(() => {98 validateConfig({99 foo: 'bar',100 backend: { name: 'bar' },101 media_folder: 'baz',102 collections: [],103 });104 }).toThrowError("'collections' should NOT have fewer than 1 items");105 });106 it('should throw if collections is an array with a single null element in config', () => {107 expect(() => {108 validateConfig({109 foo: 'bar',110 backend: { name: 'bar' },111 media_folder: 'baz',112 collections: [null],113 });114 }).toThrowError("'collections[0]' should be object");115 });116 it('should throw if local_backend is not a boolean or plain object', () => {117 expect(() => {118 validateConfig({ ...validConfig, local_backend: [] });119 }).toThrowError("'local_backend' should be boolean");120 });121 it('should throw if local_backend url is not a string', () => {122 expect(() => {123 validateConfig({ ...validConfig, local_backend: { url: [] } });124 }).toThrowError("'local_backend.url' should be string");125 });126 it('should throw if local_backend allowed_hosts is not a string array', () => {127 expect(() => {128 validateConfig({ ...validConfig, local_backend: { allowed_hosts: [true] } });129 }).toThrowError("'local_backend.allowed_hosts[0]' should be string");130 });131 it('should not throw if local_backend is a boolean', () => {132 expect(() => {133 validateConfig({ ...validConfig, local_backend: true });134 }).not.toThrowError();135 });136 it('should not throw if local_backend is a plain object with url string property', () => {137 expect(() => {138 validateConfig({ ...validConfig, local_backend: { url: 'http://localhost:8081/api/v1' } });139 }).not.toThrowError();140 });141 it('should not throw if local_backend is a plain object with allowed_hosts string array property', () => {142 expect(() => {143 validateConfig({144 ...validConfig,145 local_backend: { allowed_hosts: ['192.168.0.1'] },146 });147 }).not.toThrowError();148 });149 it('should throw if collection publish is not a boolean', () => {150 expect(() => {151 validateConfig(merge({}, validConfig, { collections: [{ publish: 'false' }] }));152 }).toThrowError("'collections[0].publish' should be boolean");153 });154 it('should not throw if collection publish is a boolean', () => {155 expect(() => {156 validateConfig(merge({}, validConfig, { collections: [{ publish: false }] }));157 }).not.toThrowError();158 });159 it('should throw if collections sortable_fields is not a boolean or a string array', () => {160 expect(() => {161 validateConfig(merge({}, validConfig, { collections: [{ sortable_fields: 'title' }] }));162 }).toThrowError("'collections[0].sortable_fields' should be array");163 });164 it('should allow sortable_fields to be a string array', () => {165 expect(() => {166 validateConfig(merge({}, validConfig, { collections: [{ sortable_fields: ['title'] }] }));167 }).not.toThrow();168 });169 it('should allow sortable_fields to be a an empty array', () => {170 expect(() => {171 validateConfig(merge({}, validConfig, { collections: [{ sortable_fields: [] }] }));172 }).not.toThrow();173 });174 it('should allow sortableFields instead of sortable_fields', () => {175 expect(() => {176 validateConfig(merge({}, validConfig, { collections: [{ sortableFields: [] }] }));177 }).not.toThrow();178 });179 it('should throw if both sortable_fields and sortableFields exist', () => {180 expect(() => {181 validateConfig(182 merge({}, validConfig, { collections: [{ sortable_fields: [], sortableFields: [] }] }),183 );184 }).toThrowError("'collections[0]' should NOT be valid");185 });186 it('should throw if collection names are not unique', () => {187 expect(() => {188 validateConfig(189 merge({}, validConfig, {190 collections: [validConfig.collections[0], validConfig.collections[0]],191 }),192 );193 }).toThrowError("'collections' collections names must be unique");194 });195 it('should throw if collection file names are not unique', () => {196 expect(() => {197 validateConfig(198 merge({}, validConfig, {199 collections: [200 {},201 {202 files: [203 {204 name: 'a',205 label: 'a',206 file: 'a.md',207 fields: [{ name: 'title', label: 'title', widget: 'string' }],208 },209 {210 name: 'a',211 label: 'b',212 file: 'b.md',213 fields: [{ name: 'title', label: 'title', widget: 'string' }],214 },215 ],216 },217 ],218 }),219 );220 }).toThrowError("'collections[1].files' files names must be unique");221 });222 it('should throw if collection fields names are not unique', () => {223 expect(() => {224 validateConfig(225 merge({}, validConfig, {226 collections: [227 {228 fields: [229 { name: 'title', label: 'title', widget: 'string' },230 { name: 'title', label: 'other title', widget: 'string' },231 ],232 },233 ],234 }),235 );236 }).toThrowError("'collections[0].fields' fields names must be unique");237 });238 it('should not throw if collection fields are unique across nesting levels', () => {239 expect(() => {240 validateConfig(241 merge({}, validConfig, {242 collections: [243 {244 fields: [245 { name: 'title', label: 'title', widget: 'string' },246 {247 name: 'object',248 label: 'Object',249 widget: 'object',250 fields: [{ name: 'title', label: 'title', widget: 'string' }],251 },252 ],253 },254 ],255 }),256 );257 }).not.toThrow();258 });259 describe('nested validation', () => {260 const { getWidgets } = require('../../lib/registry');261 getWidgets.mockImplementation(() => [262 {263 name: 'relation',264 schema: {265 properties: {266 search_fields: { type: 'array', items: { type: 'string' } },267 display_fields: { type: 'array', items: { type: 'string' } },268 },269 },270 },271 ]);272 it('should throw if nested relation display_fields and search_fields are not arrays', () => {273 expect(() => {274 validateConfig(275 merge({}, validConfig, {276 collections: [277 {278 fields: [279 { name: 'title', label: 'title', widget: 'string' },280 {281 name: 'object',282 label: 'Object',283 widget: 'object',284 fields: [285 { name: 'title', label: 'title', widget: 'string' },286 {287 name: 'relation',288 label: 'relation',289 widget: 'relation',290 display_fields: 'title',291 search_fields: 'title',292 },293 ],294 },295 ],296 },297 ],298 }),299 );300 }).toThrowError("'search_fields' should be array\n'display_fields' should be array");301 });302 it('should not throw if nested relation display_fields and search_fields are arrays', () => {303 expect(() => {304 validateConfig(305 merge({}, validConfig, {306 collections: [307 {308 fields: [309 { name: 'title', label: 'title', widget: 'string' },310 {311 name: 'object',312 label: 'Object',313 widget: 'object',314 fields: [315 { name: 'title', label: 'title', widget: 'string' },316 {317 name: 'relation',318 label: 'relation',319 widget: 'relation',320 display_fields: ['title'],321 search_fields: ['title'],322 },323 ],324 },325 ],326 },327 ],328 }),329 );330 }).not.toThrow();331 });332 });333 it('should throw if collection meta is not a plain object', () => {334 expect(() => {335 validateConfig(merge({}, validConfig, { collections: [{ meta: [] }] }));336 }).toThrowError("'collections[0].meta' should be object");337 });338 it('should throw if collection meta is an empty object', () => {339 expect(() => {340 validateConfig(merge({}, validConfig, { collections: [{ meta: {} }] }));341 }).toThrowError("'collections[0].meta' should NOT have fewer than 1 properties");342 });343 it('should throw if collection meta is an empty object', () => {344 expect(() => {345 validateConfig(merge({}, validConfig, { collections: [{ meta: { path: {} } }] }));346 }).toThrowError("'collections[0].meta.path' should have required property 'label'");347 expect(() => {348 validateConfig(349 merge({}, validConfig, { collections: [{ meta: { path: { label: 'Label' } } }] }),350 );351 }).toThrowError("'collections[0].meta.path' should have required property 'widget'");352 expect(() => {353 validateConfig(354 merge({}, validConfig, {355 collections: [{ meta: { path: { label: 'Label', widget: 'widget' } } }],356 }),357 );358 }).toThrowError("'collections[0].meta.path' should have required property 'index_file'");359 });360 it('should allow collection meta to have a path configuration', () => {361 expect(() => {362 validateConfig(363 merge({}, validConfig, {364 collections: [365 { meta: { path: { label: 'Path', widget: 'string', index_file: 'index' } } },366 ],367 }),368 );369 }).not.toThrow();370 });371 it('should throw if collection field pattern is not an array', () => {372 expect(() => {373 validateConfig(merge({}, validConfig, { collections: [{ fields: [{ pattern: '' }] }] }));374 }).toThrowError("'collections[0].fields[0].pattern' should be array");375 });376 it('should throw if collection field pattern is not an array of [string|regex, string]', () => {377 expect(() => {378 validateConfig(379 merge({}, validConfig, { collections: [{ fields: [{ pattern: [1, ''] }] }] }),380 );381 }).toThrowError(382 "'collections[0].fields[0].pattern[0]' should be string\n'collections[0].fields[0].pattern[0]' should be a regular expression",383 );384 expect(() => {385 validateConfig(386 merge({}, validConfig, { collections: [{ fields: [{ pattern: ['', 1] }] }] }),387 );388 }).toThrowError("'collections[0].fields[0].pattern[1]' should be string");389 });390 it('should allow collection field pattern to be an array of [string|regex, string]', () => {391 expect(() => {392 validateConfig(393 merge({}, validConfig, {394 collections: [{ fields: [{ pattern: ['pattern', 'error'] }] }],395 }),396 );397 }).not.toThrow();398 expect(() => {399 validateConfig(400 merge({}, validConfig, {401 collections: [{ fields: [{ pattern: [/pattern/, 'error'] }] }],402 }),403 );404 }).not.toThrow();405 });406 });...

Full Screen

Full Screen

mongodbhandler.js

Source:mongodbhandler.js Github

copy

Full Screen

1import Moment from 'moment';2import mongoose from 'mongoose';3import Logger from '../misc/logger.js';4import ObjectValidator from '../misc/objectvalidator.js';5import File from '../models/nosql/File.js';6import path from 'path';7class FCMongoDBHandler{8 constructor(config){9 this.config_provided = config;10 this.config = {11 system: null,12 url: null,13 tableName: null,14 properDelete: null,15 };16 this.mongoose = mongoose;17 }18 async connect(){19 const self = this;20 const validateConfig = await ObjectValidator.validate({ object: this.config_provided, against: "MongoDBHandler", });21 if(validateConfig.success){22 this.config = validateConfig.object;23 this.FileModel = File({ t: validateConfig.object.tableName, });24 return await this.connectToDatabase();25 Logger.log("New FCMongoDBHandler initialized");26 }else{ Logger.log("New FCMongoDBHandler initialization failed"); }27 return false;28 }29 // Private function.30 // Connects to the database.31 async connectToDatabase(){32 try{33 await this.mongoose.connect(this.config.url, {34 useUnifiedTopology: true,35 useNewUrlParser: true,36 useFindAndModify: false37 });38 Logger.log('Connection with database has been established successfully.');39 return true;40 }catch(error){ Logger.log('Unable to connect to the database:', error); }41 return false;42 }43 // Creates new table.44 async createTable(){45 try{46 Logger.log("Creating table");47 await this.FileModel.collection.drop();48 Logger.log("Table created");49 }catch(error){50 Logger.log(error);51 return true; // Collection does not exists, therefore can not be dropped.52 }53 return true;54 }55 // Private function.56 // Gets files entry from the database.57 async getAllModels(options){58 const validateConfig = await ObjectValidator.validate({ object: options, against: "Func_GetAllModels", });59 let found = [];60 let toReturn = [];61 if(validateConfig.success){62 if(validateConfig.object.userId){63 if(validateConfig.object.folder){64 if(validateConfig.object.folder.toString().trim() === "*"){65 found = await this.FileModel.find({ isDeleted: false, userId: validateConfig.object.userId, });66 }else{67 found = await this.FileModel.find({ isDeleted: false, userId: validateConfig.object.userId, folder: validateConfig.object.folder, });68 }69 }else{70 found = await this.FileModel.find({ isDeleted: false, userId: validateConfig.object.userId, });71 }72 }else{73 if(validateConfig.object.folder){74 if(validateConfig.object.folder.toString().trim() === "*"){75 found = await this.FileModel.find({ isDeleted: false, });76 }else{77 found = await this.FileModel.find({ isDeleted: false, folder: validateConfig.object.folder, });78 }79 }else{80 found = await this.FileModel.find({ isDeleted: false, });81 }82 }83 }84 if(Array.isArray(found)){85 for(let each of found){86 if(each){87 try{88 toReturn.push(await each.renameId());89 }catch(error){ Logger.log(error); }90 }91 }92 }93 return toReturn;94 }95 // Private function.96 // Gets file entry from the database.97 async getModel(options){98 try{99 if(typeof options === "object"){100 let model = null;101 if(options.id){102 if(options.userId){103 model = await this.FileModel.findOne({ _id: options.id, userId: options.userId, isDeleted: false, });104 }else{105 model = await this.FileModel.findOne({ _id: options.id, isDeleted: false, });106 }107 }else{108 if(options.path){109 if(options.userId){110 model = await this.FileModel.findOne({ path: options.path, userId: options.userId, isDeleted: false, });111 }else{112 model = await this.FileModel.findOne({ path: options.path, isDeleted: false, });113 }114 }115 }116 if(model){117 try{118 return await model.renameId();119 }catch(error){ Logger.log(error); }120 }121 }122 }catch(error){123 Logger.log(error);124 }125 return null;126 }127 // Private function.128 // Creates file entry in the database.129 async newModel(options){130 const validateConfig = await ObjectValidator.validate({ object: options, against: "Func_NewModel", });131 if(validateConfig.success){132 try{133 let path = `${validateConfig.object.folder}${validateConfig.object.folder === "" ? "" : "/"}${validateConfig.object.name}.${validateConfig.object.ext}`;134 await this.FileModel.create({ userId: validateConfig.object.userId, name: validateConfig.object.name, extension: validateConfig.object.ext, folder: validateConfig.object.folder, size: validateConfig.object.size, isEncrypted: validateConfig.object.isEncrypted, path: path, });135 return await this.getModel({ path });136 }catch(error){ Logger.log(error); }137 }138 return null;139 }140 // Private function.141 // Deletes/Updates file entry from/in the database.142 async deleteModel(options){143 const validateConfig = await ObjectValidator.validate({ object: options, against: "Func_DeleteModel", });144 if(validateConfig.success){145 try{146 let utcStamp = Moment.utc().valueOf();147 let updates = { isDeleted: true, deleted_at: utcStamp, };148 let config = { upsert: false };149 if(this.config.properDelete === false){150 if(validateConfig.object.id){151 if(validateConfig.object.userId){152 return await this.FileModel.findOneAndUpdate({153 _id: validateConfig.object.id,154 isDeleted: false,155 userId: validateConfig.object.userId,156 }, updates, config).then(message => { return true; }).catch(error => { return false; });157 }else{158 return await this.FileModel.findOneAndUpdate({159 _id: validateConfig.object.id,160 isDeleted: false,161 }, updates, config).then(message => { return true; }).catch(error => { return false; });162 }163 }else{164 if(validateConfig.object.path){165 if(validateConfig.object.userId){166 return await this.FileModel.findOneAndUpdate({167 path: validateConfig.object.path,168 isDeleted: false,169 userId: validateConfig.object.userId,170 }, updates, config).then(message => { return true; }).catch(error => { return false; });171 }else{172 return await this.FileModel.findOneAndUpdate({173 path: validateConfig.object.path,174 isDeleted: false,175 }, updates, config).then(message => { return true; }).catch(error => { return false; });176 }177 }else{ return false; }178 }179 }else{180 if(validateConfig.object.id){181 if(validateConfig.object.userId){182 return await this.FileModel.findOneAndDelete({ _id: validateConfig.object.id, isDeleted: false, userId: validateConfig.object.userId, }).then(message => { return true; }).catch(error => { return false; });183 }else{184 return await this.FileModel.findOneAndDelete({ _id: validateConfig.object.id, isDeleted: false, }).then(message => { return true; }).catch(error => { return false; });185 }186 }else{187 if(validateConfig.object.path){188 if(validateConfig.object.userId){189 return await this.FileModel.findOneAndDelete({ path: validateConfig.object.path, isDeleted: false, userId: validateConfig.object.userId, }).then(message => { return true; }).catch(error => { return false; });190 }else{191 return await this.FileModel.findOneAndDelete({ path: validateConfig.object.path, isDeleted: false, }).then(message => { return true; }).catch(error => { return false; });192 }193 }else{ return false; }194 }195 }196 return true;197 }catch(error){ Logger.log(error); }198 }199 return false;200 }201 // Private function.202 // Updates file entry in the database.203 async updateModel(options){204 const validateConfig = await ObjectValidator.validate({ object: options, against: "Func_UpdateModel", });205 if(validateConfig.success){206 try{207 const model = await this.FileModel.findOne(208 validateConfig.object.id && validateConfig.object.userId ? { _id: validateConfig.object.id, isDeleted: false, userId: validateConfig.object.userId, }209 : validateConfig.object.id ? { _id: validateConfig.object.id, isDeleted: false, }210 : validateConfig.object.path && validateConfig.object.userId ? { path: validateConfig.object.path, isDeleted: false, userId: validateConfig.object.userId, }211 : validateConfig.object.path ? { path: validateConfig.object.path, isDeleted: false, }212 : { _id: null, }213 );214 if(!model){ return false; }215 let updates = { };216 if(validateConfig.object.newName){217 const newFilePath = `${model.folder}${model.folder === "" ? "" : "/"}${validateConfig.object.newName}.${model.extension}`;218 updates = { name: validateConfig.object.newName, path: newFilePath };219 }else{220 if(validateConfig.object.isEncrypted !== undefined && validateConfig.object.isEncrypted !== null){221 updates = { isEncrypted: validateConfig.object.isEncrypted };222 }else{223 if(validateConfig.object.size !== undefined && validateConfig.object.size !== null){224 updates = { size: validateConfig.object.size };225 }else{226 if(validateConfig.object.newPath){227 const folderFromPath = path.dirname(validateConfig.object.newPath);228 const newFilePath = `${folderFromPath}${folderFromPath === "" ? "" : "/"}${model.name}.${model.extension}`;229 updates = { folder: folderFromPath, path: newFilePath };230 }231 }232 }233 }234 let config = { upsert: false };235 if(validateConfig.object.id){236 if(validateConfig.object.userId){237 return await this.FileModel.findOneAndUpdate({ _id: validateConfig.object.id, isDeleted: false, userId: validateConfig.object.userId, }, updates, config).then(message => { return true; }).catch(error => { return false; });238 }else{239 return await this.FileModel.findOneAndUpdate({ _id: validateConfig.object.id, isDeleted: false, }, updates, config).then(message => { return true; }).catch(error => { return false; });240 }241 }else{242 if(validateConfig.object.path){243 if(validateConfig.object.userId){244 return await this.FileModel.findOneAndUpdate({ path: validateConfig.object.path, isDeleted: false, userId: validateConfig.object.userId, }, updates, config).then(message => { return true; }).catch(error => { return false; });245 }else{246 return await this.FileModel.findOneAndUpdate({ path: validateConfig.object.path, isDeleted: false, }, updates, config).then(message => { return true; }).catch(error => { return false; });247 }248 }else{ return false; }249 }250 return true;251 }catch(error){ Logger.log(error); }252 }253 return false;254 }255}...

Full Screen

Full Screen

config-test.js

Source:config-test.js Github

copy

Full Screen

...28 t.ok(validateConfig, 'Config validator is present')29})30test('Do nothing', t => {31 t.plan(1)32 validateConfig(params, defaults, errors)33 t.equal(errors.length, 0, `No errors reported`)34 t.teardown(reset)35})36test('Valid config', t => {37 t.plan(5)38 defaults.aws.runtime = okRuntime39 defaults.aws.memory = okMemory40 defaults.aws.storage = okStorage41 defaults.aws.timeout = okTimeout42 validateConfig(params, defaults, errors)43 t.equal(errors.length, 0, `No errors reported (global config)`)44 defaults.aws.runtime = 'node'45 validateConfig(params, defaults, errors)46 t.equal(errors.length, 0, `No errors reported (global config)`)47 defaults.aws.runtime = 'node.js'48 validateConfig(params, defaults, errors)49 t.equal(errors.length, 0, `No errors reported (global config)`)50 defaults.aws.runtime = 'Node.js'51 validateConfig(params, defaults, errors)52 t.equal(errors.length, 0, `No errors reported (global config)`)53 reset()54 defaults.events = createPragma(okMemory, okRuntime, okStorage, okTimeout)55 validateConfig(params, defaults, errors)56 t.equal(errors.length, 0, `No errors reported (function config)`)57 t.teardown(reset)58})59/**60 * Memory61 */62test('Minimum memory not met', t => {63 t.plan(6)64 defaults.aws.memory = 12765 validateConfig(params, defaults, errors)66 t.equal(errors.length, 1, `Error reported (global config)`)67 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)68 reset()69 defaults.events = createPragma(127, okRuntime, okStorage, okTimeout)70 validateConfig(params, defaults, errors)71 t.equal(errors.length, 1, `Error reported (function config)`)72 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)73 reset()74 defaults.aws.memory = 12775 defaults.events = createPragma(127, okRuntime, okStorage, okTimeout)76 validateConfig(params, defaults, errors)77 t.equal(errors.length, 1, `Error reported (global + function config match)`)78 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)79 t.teardown(reset)80})81test('Maximum memory exceeded', t => {82 t.plan(6)83 defaults.aws.memory = 1024184 validateConfig(params, defaults, errors)85 t.equal(errors.length, 1, `Error reported (global config)`)86 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)87 reset()88 defaults.events = createPragma(10241, okRuntime, okStorage, okTimeout)89 validateConfig(params, defaults, errors)90 t.equal(errors.length, 1, `Error reported (function config)`)91 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)92 reset()93 defaults.aws.memory = 1024194 defaults.events = createPragma(10241, okRuntime, okStorage, okTimeout)95 validateConfig(params, defaults, errors)96 t.equal(errors.length, 1, `Error reported (global + function config match)`)97 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)98 t.teardown(reset)99})100test('Memory is invalid', t => {101 t.plan(6)102 defaults.aws.memory = 1.01103 validateConfig(params, defaults, errors)104 t.equal(errors.length, 1, `Error reported (global config)`)105 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)106 reset()107 defaults.events = createPragma(1.01, okRuntime, okStorage, okTimeout)108 validateConfig(params, defaults, errors)109 t.equal(errors.length, 1, `Error reported (function config)`)110 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)111 reset()112 defaults.aws.memory = 1.01113 defaults.events = createPragma(1.01, okRuntime, okStorage, okTimeout)114 validateConfig(params, defaults, errors)115 t.equal(errors.length, 1, `Error reported (global + function config match)`)116 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)117 t.teardown(reset)118})119/**120 * Runtime121 */122test('Runtime is invalid', t => {123 t.plan(6)124 let runtime = 'fail'125 defaults.aws.runtime = runtime126 validateConfig(params, defaults, errors)127 t.equal(errors.length, 1, `Error reported (global config)`)128 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)129 reset()130 defaults.events = createPragma(okMemory, runtime, okStorage, okTimeout)131 validateConfig(params, defaults, errors)132 t.equal(errors.length, 1, `Error reported (function config)`)133 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)134 reset()135 defaults.aws.runtime = runtime136 defaults.events = createPragma(okMemory, runtime, okStorage, okTimeout)137 validateConfig(params, defaults, errors)138 t.equal(errors.length, 1, `Error reported (global + function config match)`)139 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)140 t.teardown(reset)141})142/**143 * Storage144 */145test('Minimum storage not met', t => {146 t.plan(6)147 defaults.aws.storage = 127148 validateConfig(params, defaults, errors)149 t.equal(errors.length, 1, `Error reported (global config)`)150 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)151 reset()152 defaults.events = createPragma(okMemory, okRuntime, 127, okTimeout)153 validateConfig(params, defaults, errors)154 t.equal(errors.length, 1, `Error reported (function config)`)155 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)156 reset()157 defaults.aws.storage = 127158 defaults.events = createPragma(okMemory, okRuntime, 127, okTimeout)159 validateConfig(params, defaults, errors)160 t.equal(errors.length, 1, `Error reported (global + function config match)`)161 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)162 t.teardown(reset)163})164test('Maximum storage exceeded', t => {165 t.plan(6)166 defaults.aws.storage = 10241167 validateConfig(params, defaults, errors)168 t.equal(errors.length, 1, `Error reported (global config)`)169 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)170 reset()171 defaults.events = createPragma(okMemory, okRuntime, 10241, okTimeout)172 validateConfig(params, defaults, errors)173 t.equal(errors.length, 1, `Error reported (function config)`)174 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)175 reset()176 defaults.aws.storage = 10241177 defaults.events = createPragma(okMemory, okRuntime, 10241, okTimeout)178 validateConfig(params, defaults, errors)179 t.equal(errors.length, 1, `Error reported (global + function config match)`)180 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)181 t.teardown(reset)182})183test('Storage is invalid', t => {184 t.plan(6)185 defaults.aws.storage = 1.01186 validateConfig(params, defaults, errors)187 t.equal(errors.length, 1, `Error reported (global config)`)188 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)189 reset()190 defaults.events = createPragma(okMemory, okRuntime, 1.01, okTimeout)191 validateConfig(params, defaults, errors)192 t.equal(errors.length, 1, `Error reported (function config)`)193 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)194 reset()195 defaults.aws.storage = 1.01196 defaults.events = createPragma(okMemory, okRuntime, 1.01, okTimeout)197 validateConfig(params, defaults, errors)198 t.equal(errors.length, 1, `Error reported (global + function config match)`)199 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)200 t.teardown(reset)201})202/**203 * Timeout204 */205test('Minimum timeout not met', t => {206 t.plan(6)207 defaults.aws.timeout = 0208 validateConfig(params, defaults, errors)209 t.equal(errors.length, 1, `Error reported (global config)`)210 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)211 reset()212 defaults.events = createPragma(okMemory, okRuntime, okStorage, 0)213 validateConfig(params, defaults, errors)214 t.equal(errors.length, 1, `Error reported (function config)`)215 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)216 reset()217 defaults.aws.timeout = 0218 defaults.events = createPragma(okMemory, okRuntime, okStorage, 0)219 validateConfig(params, defaults, errors)220 t.equal(errors.length, 1, `Error reported (global + function config match)`)221 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)222 t.teardown(reset)223})224test('Maximum timeout exceeded', t => {225 t.plan(6)226 let timeout = 1 * 60 * 15 + 1227 defaults.aws.timeout = timeout228 validateConfig(params, defaults, errors)229 t.equal(errors.length, 1, `Error reported (global config)`)230 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)231 reset()232 defaults.events = createPragma(okMemory, okRuntime, okStorage, timeout)233 validateConfig(params, defaults, errors)234 t.equal(errors.length, 1, `Error reported (function config)`)235 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)236 reset()237 defaults.aws.timeout = timeout238 defaults.events = createPragma(okMemory, okRuntime, okStorage, timeout)239 validateConfig(params, defaults, errors)240 t.equal(errors.length, 1, `Error reported (global + function config match)`)241 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)242 t.teardown(reset)243})244test('Timeout is invalid', t => {245 t.plan(6)246 defaults.aws.timeout = 1.01247 validateConfig(params, defaults, errors)248 t.equal(errors.length, 1, `Error reported (global config)`)249 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)250 reset()251 defaults.events = createPragma(okMemory, okRuntime, okStorage, 1.01)252 validateConfig(params, defaults, errors)253 t.equal(errors.length, 1, `Error reported (function config)`)254 t.ok(errors[0].includes(name), `Configuration error is Lambda-specific`)255 reset()256 defaults.aws.timeout = 1.01257 defaults.events = createPragma(okMemory, okRuntime, okStorage, 1.01)258 validateConfig(params, defaults, errors)259 t.equal(errors.length, 1, `Error reported (global + function config match)`)260 t.ok(!errors[0].includes(name), `Configuration error is not Lambda-specific`)261 t.teardown(reset)...

Full Screen

Full Screen

utils.test.js

Source:utils.test.js Github

copy

Full Screen

...32 context.mock(() => {33 path.resolve = () => "";34 fs.existsSync = () => false;35 });36 const result = validateConfig({}, "/Users/misha/oscar");37 assert.equal(result, {38 errors: [`crawlFrom is missing`],39 });40});41ValidateConfig("crawlFrom should be a string", (context) => {42 context.mock(() => {43 path.resolve = () => "";44 fs.existsSync = () => false;45 });46 const result = validateConfig(47 {48 crawlFrom: true,49 },50 "/Users/misha/oscar"51 );52 assert.equal(result, {53 errors: [`crawlFrom should be a string`],54 });55});56ValidateConfig("crawlFrom path doesn't exist", (context) => {57 context.mock(() => {58 fs.existsSync = () => false;59 });60 const result = validateConfig(61 {62 crawlFrom: "./src",63 },64 "/Users/misha/oscar"65 );66 assert.equal(result, {67 errors: [`crawlFrom path doesn't exist (/Users/misha/oscar/src)`],68 });69});70ValidateConfig("exclude is an array with invalid items", () => {71 const result = validateConfig(72 {73 crawlFrom: "./src",74 exclude: ["utils", /node_modules/, undefined],75 },76 "/Users/misha/oscar"77 );78 assert.equal(result, {79 crawlFrom: "/Users/misha/oscar/src",80 errors: [81 `every item in the exclude array should be a string or a regex (undefined found)`,82 ],83 });84});85ValidateConfig("exclude is neither an array nor a function", () => {86 const result = validateConfig(87 {88 crawlFrom: "./src",89 exclude: "utils",90 },91 "/Users/misha/oscar"92 );93 assert.equal(result, {94 crawlFrom: "/Users/misha/oscar/src",95 errors: [`exclude should be an array or a function`],96 });97});98ValidateConfig("globs is not an array", () => {99 const result = validateConfig(100 {101 crawlFrom: "./src",102 globs: "**/*.js",103 },104 "/Users/misha/oscar"105 );106 assert.equal(result, {107 crawlFrom: "/Users/misha/oscar/src",108 errors: [`globs should be an array`],109 });110});111ValidateConfig("globs has a non string item", () => {112 const result = validateConfig(113 {114 crawlFrom: "./src",115 globs: ["**/*.js", 4],116 },117 "/Users/misha/oscar"118 );119 assert.equal(result, {120 crawlFrom: "/Users/misha/oscar/src",121 errors: [`every item in the globs array should be a string (number found)`],122 });123});124ValidateConfig("components is not an object", () => {125 const result = validateConfig(126 {127 crawlFrom: "./src",128 components: "Header",129 },130 "/Users/misha/oscar"131 );132 assert.equal(result, {133 crawlFrom: "/Users/misha/oscar/src",134 errors: [`components should be an object`],135 });136});137ValidateConfig("components has a non true value", () => {138 const result = validateConfig(139 {140 crawlFrom: "./src",141 components: {142 Header: false,143 },144 },145 "/Users/misha/oscar"146 );147 assert.equal(result, {148 crawlFrom: "/Users/misha/oscar/src",149 errors: [`the only supported value in the components object is true`],150 });151});152ValidateConfig("includeSubComponents is not a boolean", () => {153 const result = validateConfig(154 {155 crawlFrom: "./src",156 includeSubComponents: "yes",157 },158 "/Users/misha/oscar"159 );160 assert.equal(result, {161 crawlFrom: "/Users/misha/oscar/src",162 errors: [`includeSubComponents should be a boolean`],163 });164});165ValidateConfig("importedFrom is not a string or a RegExp", () => {166 const result = validateConfig(167 {168 crawlFrom: "./src",169 importedFrom: ["basis"],170 },171 "/Users/misha/oscar"172 );173 assert.equal(result, {174 crawlFrom: "/Users/misha/oscar/src",175 errors: [`importedFrom should be a string or a RegExp`],176 });177});178ValidateConfig("processors is not an array", () => {179 const result = validateConfig(180 {181 crawlFrom: "./src",182 processors: "count-components",183 },184 "/Users/misha/oscar"185 );186 assert.equal(result, {187 crawlFrom: "/Users/misha/oscar/src",188 errors: [`processors should be an array`],189 });190});191ValidateConfig("string form - unknown processor", () => {192 const result = validateConfig(193 {194 crawlFrom: "./src",195 processors: ["foo"],196 },197 "/Users/misha/oscar"198 );199 assert.is(result.crawlFrom, "/Users/misha/oscar/src");200 assert.is(result.errors.length, 1);201 assert.ok(/^unknown processor: foo/.test(result.errors[0]));202});203ValidateConfig("array form - not a tuple", () => {204 const result = validateConfig(205 {206 crawlFrom: "./src",207 processors: [["count-components"]],208 },209 "/Users/misha/oscar"210 );211 assert.equal(result, {212 crawlFrom: "/Users/misha/oscar/src",213 errors: [214 `processor is in a form of array should have exactly 2 items (1 item found)`,215 ],216 });217});218ValidateConfig("array form - processor name is not a string", () => {219 const result = validateConfig(220 {221 crawlFrom: "./src",222 processors: [[() => {}, "count-components"]],223 },224 "/Users/misha/oscar"225 );226 assert.equal(result, {227 crawlFrom: "/Users/misha/oscar/src",228 errors: [229 `when processor is a tuple, the first item is a name and should be a string (function found)`,230 ],231 });232});233ValidateConfig("array form - unknown processor", () => {234 const result = validateConfig(235 {236 crawlFrom: "./src",237 processors: [["foo", {}]],238 },239 "/Users/misha/oscar"240 );241 assert.is(result.crawlFrom, "/Users/misha/oscar/src");242 assert.is(result.errors.length, 1);243 assert.ok(/^unknown processor: foo/.test(result.errors[0]));244});245ValidateConfig("array form - processor options is not an object", () => {246 const result = validateConfig(247 {248 crawlFrom: "./src",249 processors: [["count-components", () => {}]],250 },251 "/Users/misha/oscar"252 );253 assert.equal(result, {254 crawlFrom: "/Users/misha/oscar/src",255 errors: [256 `when processor is a tuple, the second item is options and should be an object`,257 ],258 });259});260ValidateConfig("array form - processor name is unsupported type", () => {261 const result = validateConfig(262 {263 crawlFrom: "./src",264 processors: [true, () => {}],265 },266 "/Users/misha/oscar"267 );268 assert.equal(result, {269 crawlFrom: "/Users/misha/oscar/src",270 errors: [271 `processor should be a string, an array, or a function (boolean found)`,272 ],273 });274});275ValidateConfig("valid config with all options", () => {276 const result = validateConfig(277 {278 crawlFrom: "./src",279 exclude: ["utils"],280 globs: ["**/*.js"],281 components: {282 Button: true,283 Footer: true,284 Text: true,285 },286 includeSubComponents: true,287 importedFrom: "basis",288 processors: ["count-components"],289 },290 "/Users/misha/oscar"...

Full Screen

Full Screen

validate-config.js

Source:validate-config.js Github

copy

Full Screen

1/* eslint-disable */2const chai = require('chai');3const dirtyChai = require('dirty-chai');4const simple = require('simple-mock');5const { expect } = chai;6chai.use(dirtyChai);7const ValidateConfig = require('../app/validate-config.js');8describe('ValidateConfig', () => {9 describe('constructor', () => {10 it('should instanciate the class', () => {11 const validateConfig = new ValidateConfig();12 expect(typeof validateConfig).to.equal('object');13 expect(typeof validateConfig.validate).to.equal('function');14 });15 });16 describe('isNull', () => {17 it('should return false if config is not null', () => {18 const config = 'some';19 const validateConfig = new ValidateConfig();20 const result = validateConfig.isNull(config);21 expect(typeof result).to.equal('boolean');22 expect(result).to.equal(false);23 });24 it('should throw an error if config is null', () => {25 const config = null;26 const Log = new Object();27 simple.mock(Log, 'debug');28 Log.debug.returnWith(true);29 const validateConfig = new ValidateConfig(Log);30 chai.assert.throw(31 function () {32 validateConfig.isNull(config)33 },34 Error,35 "Error on load config see the file ./config/redis.js"36 );37 });38 });39 describe('notArray', () => {40 it('should return false if config is an array', () => {41 const config = [];42 const validateConfig = new ValidateConfig();43 const result = validateConfig.notArray(config);44 expect(typeof result).to.equal('boolean');45 expect(result).to.equal(false);46 });47 it('should throw an error if config is not an array', () => {48 const config = null;49 const Log = new Object();50 simple.mock(Log, 'debug');51 Log.debug.returnWith(true);52 const validateConfig = new ValidateConfig(Log);53 chai.assert.throw(54 function () {55 validateConfig.notArray(config)56 },57 Error,58 "Error on load config see the file ./config/redis.js"59 );60 });61 });62 describe('isEmpty', () => {63 it('should return false if config is not empty', () => {64 const config = [1];65 const validateConfig = new ValidateConfig();66 const result = validateConfig.isEmpty(config);67 expect(typeof result).to.equal('boolean');68 expect(result).to.equal(false);69 });70 it('should throw an error if config is empty', () => {71 const config = [];72 const Log = new Object();73 simple.mock(Log, 'debug');74 Log.debug.returnWith(true);75 const validateConfig = new ValidateConfig(Log);76 chai.assert.throw(77 function () {78 validateConfig.isEmpty(config)79 },80 Error,81 "Error on load config see the file ./config/redis.js"82 );83 });84 });85 describe('elementNotObject', () => {86 it('should return false if config element is an object', () => {87 const config = [88 {89 prop: 1,90 },91 ];92 const validateConfig = new ValidateConfig();93 const result = validateConfig.elementNotObject(config, 0);94 expect(typeof result).to.equal('boolean');95 expect(result).to.equal(false);96 });97 it('should throw an error if config is empty', () => {98 const config = [1];99 const Log = new Object();100 simple.mock(Log, 'debug');101 Log.debug.returnWith(true);102 const validateConfig = new ValidateConfig(Log);103 chai.assert.throw(104 function () {105 validateConfig.elementNotObject(config, 0)106 },107 Error,108 "Error on load config see the file ./config/redis.js"109 );110 });111 });112 describe('elementMissingHost', () => {113 it('should return false if config element has host property', () => {114 const config = [115 {116 host: 1,117 },118 ];119 const validateConfig = new ValidateConfig();120 const result = validateConfig.elementMissingHost(config, 0);121 expect(typeof result).to.equal('boolean');122 expect(result).to.equal(false);123 });124 it('should throw an error if config is empty', () => {125 const config = [126 {127 prop: 1,128 },129 ];130 const Log = new Object();131 simple.mock(Log, 'debug');132 Log.debug.returnWith(true);133 const validateConfig = new ValidateConfig(Log);134 chai.assert.throw(135 function () {136 validateConfig.elementMissingHost(config, 0)137 },138 Error,139 "Error on load config see the file ./config/redis.js"140 );141 });142 });143 describe('elementMissingPort', () => {144 it('should return false if config element has host property', () => {145 const config = [146 {147 port: 1,148 },149 ];150 const validateConfig = new ValidateConfig();151 const result = validateConfig.elementMissingPort(config, 0);152 expect(typeof result).to.equal('boolean');153 expect(result).to.equal(false);154 });155 it('should throw an error if config is empty', () => {156 const config = [157 {158 prop: 1,159 },160 ];161 const Log = new Object();162 simple.mock(Log, 'debug');163 Log.debug.returnWith(true);164 const validateConfig = new ValidateConfig(Log);165 chai.assert.throw(166 function () {167 validateConfig.elementMissingPort(config, 0)168 },169 Error,170 "Error on load config see the file ./config/redis.js"171 );172 });173 });174 describe('elementHostNotString', () => {175 it('should return false if config element has host property', () => {176 const config = [177 {178 host: 'string',179 },180 ];181 const validateConfig = new ValidateConfig();182 const result = validateConfig.elementHostNotString(config, 0);183 expect(typeof result).to.equal('boolean');184 expect(result).to.equal(false);185 });186 it('should throw an error if config is empty', () => {187 const config = [188 {189 host: 1,190 },191 ];192 const Log = new Object();193 simple.mock(Log, 'debug');194 Log.debug.returnWith(true);195 const validateConfig = new ValidateConfig(Log);196 chai.assert.throw(197 function () {198 validateConfig.elementHostNotString(config, 0)199 },200 Error,201 "Error on load config see the file ./config/redis.js"202 );203 });204 });205 describe('elementPortNotNumber', () => {206 it('should return false if config element has host property', () => {207 const config = [208 {209 port: 1,210 },211 ];212 const validateConfig = new ValidateConfig();213 const result = validateConfig.elementPortNotNumber(config, 0);214 expect(typeof result).to.equal('boolean');215 expect(result).to.equal(false);216 });217 it('should throw an error if config is empty', () => {218 const config = [219 {220 port: 'string',221 },222 ];223 const Log = new Object();224 simple.mock(Log, 'debug');225 Log.debug.returnWith(true);226 const validateConfig = new ValidateConfig(Log);227 chai.assert.throw(228 function () {229 validateConfig.elementPortNotNumber(config, 0)230 },231 Error,232 "Error on load config see the file ./config/redis.js"233 );234 });235 });236 describe('elementHostEmpty', () => {237 it('should return false if config element has host property', () => {238 const config = [239 {240 host: 'string',241 },242 ];243 const validateConfig = new ValidateConfig();244 const result = validateConfig.elementHostEmpty(config, 0);245 expect(typeof result).to.equal('boolean');246 expect(result).to.equal(false);247 });248 it('should throw an error if config is empty', () => {249 const config = [250 {251 host: '',252 },253 ];254 const Log = new Object();255 simple.mock(Log, 'debug');256 Log.debug.returnWith(true);257 const validateConfig = new ValidateConfig(Log);258 chai.assert.throw(259 function () {260 validateConfig.elementHostEmpty(config, 0)261 },262 Error,263 "Error on load config see the file ./config/redis.js"264 );265 });266 });267 describe('elementHostEmpty', () => {268 it('should return false if config element has host property', () => {269 const config = [270 {271 host: 'string',272 },273 ];274 const validateConfig = new ValidateConfig();275 const result = validateConfig.elementHostEmpty(config, 0);276 expect(typeof result).to.equal('boolean');277 expect(result).to.equal(false);278 });279 it('should throw an error if config is empty', () => {280 const config = [281 {282 host: '',283 },284 ];285 const Log = new Object();286 simple.mock(Log, 'debug');287 Log.debug.returnWith(true);288 const validateConfig = new ValidateConfig(Log);289 chai.assert.throw(290 function () {291 validateConfig.elementHostEmpty(config, 0)292 },293 Error,294 "Error on load config see the file ./config/redis.js"295 );296 });297 });298 describe('elementPortEmpty', () => {299 it('should return false if config element has host property', () => {300 const config = [301 {302 port: 1,303 },304 ];305 const validateConfig = new ValidateConfig();306 const result = validateConfig.elementPortEmpty(config, 0);307 expect(typeof result).to.equal('boolean');308 expect(result).to.equal(false);309 });310 it('should throw an error if config is empty', () => {311 const config = [312 {313 port: 0,314 },315 ];316 const Log = new Object();317 simple.mock(Log, 'debug');318 Log.debug.returnWith(true);319 const validateConfig = new ValidateConfig(Log);320 chai.assert.throw(321 function () {322 validateConfig.elementPortEmpty(config, 0)323 },324 Error,325 "Error on load config see the file ./config/redis.js"326 );327 });328 });329 describe('validate', () => {330 it('should return true if config passes all valitations', () => {331 const config = [332 {333 host: 'localhost',334 port: 6379,335 },336 {337 host: 'localhost',338 port: 6380,339 },340 ];341 const validateConfig = new ValidateConfig();342 const result = validateConfig.validate(config);343 expect(typeof result).to.equal('boolean');344 expect(result).to.equal(true);345 });346 });...

Full Screen

Full Screen

load-project-sagui-config.spec.js

Source:load-project-sagui-config.spec.js Github

copy

Full Screen

1import { validateConfig } from './load-project-sagui-config'2describe('load-project-sagui-config', () => {3 describe('validateConfig', () => {4 it('pages', () => {5 validateConfig({6 pages: ['testing']7 })8 })9 it('libraries as strings', () => {10 validateConfig({11 libraries: ['button']12 })13 })14 it('libraries as objects', () => {15 validateConfig({16 libraries: [17 'button',18 {19 main: 'button',20 umdName: 'MyUIButton'21 }22 ]23 })24 })25 it('style.cssModules', () => {26 validateConfig({27 style: {28 cssModules: false29 }30 })31 })32 it('style.sourceMaps', () => {33 validateConfig({34 style: {35 sourceMaps: false36 }37 })38 })39 it('style.extract', () => {40 validateConfig({41 style: {42 extract: false43 }44 })45 })46 it('javaScript.transpileDependencies', () => {47 validateConfig({48 javaScript: {49 transpileDependencies: ['ui']50 }51 })52 })53 it('javaScript.typeCheckAll', () => {54 validateConfig({55 javaScript: {56 typeCheckAll: true57 }58 })59 })60 it('browsers', () => {61 validateConfig({62 browsers: ['> 1%']63 })64 })65 it('develop.proxy', () => {66 validateConfig({67 develop: {68 proxy: {69 '/some/path*': {70 target: 'https://other-server.example.com',71 secure: false72 }73 }74 }75 })76 })77 it('additionalWebpackConfig', () => {78 validateConfig({79 additionalWebpackConfig: {80 plugins: []81 }82 })83 })84 it('additionalKarmaConfig', () => {85 validateConfig({86 additionalKarmaConfig: {87 browsers: ['Chrome']88 }89 })90 })91 it('disableLoaders', () => {92 validateConfig({93 disableLoaders: [94 'font',95 'image',96 'javaScript',97 'style',98 'txt',99 'video',100 'yaml'101 ]102 })103 })104 })...

Full Screen

Full Screen

config.spec.js

Source:config.spec.js Github

copy

Full Screen

1import { expect } from "chai";2import validateConfig from "./config";3describe("Config validator", () => {4 it("does not throws Error if config is object", () => {5 expect(() => {validateConfig({})}).to.not.throw();6 });7 it("throws Error if config is invalid or not passed", () => {8 expect(() => {validateConfig()}).to.throw("Config is not passed or invalid.");9 expect(() => {validateConfig(null)}).to.throw("Config is not passed or invalid.");10 expect(() => {validateConfig(NaN)}).to.throw("Config is not passed or invalid.");11 expect(() => {validateConfig("string")}).to.throw("Invalid config.");12 expect(() => {validateConfig([])}).to.throw("Invalid config.");13 expect(() => {validateConfig(1)}).to.throw("Invalid config.");14 expect(() => {validateConfig(Infinity)}).to.throw("Invalid config.");15 expect(() => {validateConfig(true)}).to.throw("Invalid config.");16 expect(() => {validateConfig(() => {}) }).to.throw("Invalid config.");17 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const validateConfig = require('config-validator').validateConfig;2const config = require('./config.json');3const schema = require('./schema.json');4validateConfig(config, schema).then(() => {5}).catch((error) => {6});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateConfig } = require("./root");2const config = {3 db: {4 }5};6const isValid = validateConfig(config);7console.log(isValid);8const { config } = require("./root");9const express = require("express");10const app = express();11app.get("/", (req, res) => {12 res.send("Hello World!");13});14app.listen(config.port, () => {15 console.log(`Server started on port ${config.port}`);16});

Full Screen

Using AI Code Generation

copy

Full Screen

1var config = require('config');2var rootConfig = config.get('rootConfig');3rootConfig.validateConfig(function(err, result) {4 if (err) {5 console.log(err);6 }7 console.log(result);8});9{ valid: false,10 [ { keyword: 'required',11 params: { missingProperty: 'config' },12 message: 'should have required property \'config\'' } ] }

Full Screen

Using AI Code Generation

copy

Full Screen

1var rootModule = require('rootModule');2rootModule.validateConfig();3var validateConfig = function(){4}5exports.validateConfig = validateConfig;6var rootModule = require('rootModule');7rootModule.validateConfig();8var validateConfig = function(){9}10exports.validateConfig = validateConfig;11var rootModule = require('rootModule');12rootModule.validateConfig();13var validateConfig = function(){14}15exports.validateConfig = validateConfig;16var rootModule = require('rootModule');17rootModule.validateConfig();18var validateConfig = function(){19}20exports.validateConfig = validateConfig;21var rootModule = require('rootModule');22rootModule.validateConfig();23var validateConfig = function(){24}25exports.validateConfig = validateConfig;26var rootModule = require('rootModule');27rootModule.validateConfig();

Full Screen

Using AI Code Generation

copy

Full Screen

1const rootConfig = require('rootConfig');2rootConfig.validateConfig();3const rootConfig = require('rootConfig');4const config = rootConfig.get('configKey', 'defaultValue');5const rootConfig = require('rootConfig');6const config = rootConfig.getEnv('envKey', 'defaultValue');7MIT © [Sachin Dhawan](

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 root 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