How to use _connect method in Playwright Internal

Best JavaScript code snippet using playwright-internal

dal.js

Source:dal.js Github

copy

Full Screen

...44 });45 }46 }47 async create (desc) {48 this._connect();49 const results = await this._run(`SELECT * FROM version LIMIT 1`, []);50 if (results.length > 0) {51 throw 'Version # already exists';52 }53 await this._run(`INSERT INTO version VALUES (?)`, [desc.version]);54 this._close();55 }56 async update (desc) {57 this._connect();58 const results = await this._run(`SELECT * FROM version LIMIT 1`);59 if (results.length > 0) {60 await this._run(`UPDATE version SET version = ?`, [desc.version]);61 }62 else {63 await this._run(`INSERT INTO version VALUES (?)`, [desc.version]);64 }65 this._close();66 }67 68 async read () {69 this._connect();70 const rows = await this._run(`SELECT * FROM version LIMIT 1`);71 if (rows.length > 0) { 72 return {version: rows[0].version}73 }74 }75}76class Tags {77 constructor (folder) {78 this._fname = path.join(folder, _IMAGES_DB);79 }80 _connect () {81 this._db = new sqlite3.Database(this._fname);82 }83 _close () {84 if (this._db) {85 this._db.close();86 }87 }88 _run (sql, params) {89 // allow queries to be using asynchronously90 if (this._db) { 91 return new Promise((resolve, reject) => {92 this._db.all(sql, params, function (error, rows) {93 if (error)94 reject(error);95 else96 resolve(rows);97 });98 });99 }100 }101 async create (desc) {102 this._connect();103 const rows = await this._run(`SELECT * FROM tags WHERE uuid = ? and tag = ? LIMIT 1`,104 [desc.uuid, desc.tag]);105 if (rows.length > 0) {106 throw `UUID ${desc.uuid} and tag ${desc.tag} already exist`;107 }108 await this._run(`INSERT INTO tags VALUES (?, ?)`, [desc.uuid, desc.tag]);109 this._close();110 }111 async delete (uuid, tag) {112 this._connect();113 await this._run(`DELETE FROM tags WHERE uuid = ? AND tag = ?`, [uuid, tag]);114 this._close();115 }116 async delete_all_by_uuid (uuid) {117 this._connect();118 await this._run(`DELETE FROM tags WHERE uuid = ?`, [uuid]);119 this._close();120 }121 async read_by_uuid (uuid) {122 this._connect();123 const rows = await this._run(`SELECT * FROM tags WHERE uuid = ?`, [uuid]);124 this._close();125 return rows;126 }127 async read_by_uuids (uuids) {128 this._connect();129 if (uuids.length > 990) {130 throw `About to hit the limit of the number of uuids that can be looked up at once`;131 }132 const uuid_str = uuids.map(r => '?').join(', ');133 const rows = await this._run(`SELECT * FROM tags WHERE uuid IN (${uuid_str})`, uuids);134 this._close();135 return rows;136 }137 async read_all_tags () {138 this._connect();139 let rows = await this._run(`SELECT distinct tag FROM tags`);140 // rows = rows.map(r => ({tag: r.tag}));141 this._close();142 return rows;143 }144}145class Images {146 147 constructor (folder) {148 this._fname = path.join(folder, _IMAGES_DB);149 }150 _connect () {151 this._db = new sqlite3.Database(this._fname);152 }153 _close () {154 if (this._db) {155 this._db.close();156 }157 }158 _run (sql, params) {159 // allow queries to be using asynchronously160 if (this._db) { 161 return new Promise((resolve, reject) => {162 this._db.all(sql, params, function (error, rows) {163 if (error)164 reject(error);165 else166 resolve(rows);167 });168 });169 }170 }171 async create (desc) {172 this._connect();173 const timestamp = toISO(new Date());174 let rows = await this._run(`SELECT * FROM images WHERE uuid = ? LIMIT 1`, [desc.uuid])175 if (rows.length > 0) {176 throw `UUID ${desc.uuid} already exists`;177 }178 await this._run(`INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?)`, [179 desc.uuid,180 desc.extension,181 desc.content.join('\n\n'),182 timestamp,183 timestamp,184 null,185 desc.draft ? 1 : 0186 ]);187 this._close();188 }189 async update (desc) {190 this._connect();191 const timestamp = toISO(new Date());192 let rows = await this._run(`SELECT * FROM images WHERE uuid = ? LIMIT 1`, [desc.uuid]);193 if (rows.length > 0) {194 await this._run(`DELETE FROM images WHERE uuid = ?`, [desc.uuid]);195 }196 await this._run(`INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?)`, [197 desc.uuid,198 desc.extension,199 desc.content.join('\n\n'),200 toISO(desc.date_created),201 timestamp,202 desc.date_published && desc.draft == 0 ? toISO(desc.date_published) : null,203 desc.draft ? 1 : 0204 ]);205 this._close();206 }207 async delete (uuid) {208 this._connect();209 await this._run(`DELETE FROM images WHERE uuid = ?`, [uuid]);210 this._close();211 }212 _process_row (r) {213 return { uuid: r.uuid,214 extension: r.extension,215 content: r.content.split('\n\n'),216 date_created: new Date(r.date_created),217 date_updated: new Date(r.date_updated),218 date_published: r.date_published ? new Date(r.date_published) : null,219 draft: r.draft ? true : false }220 }221 async count_all () {222 this._connect();223 const rows = await this._run(`SELECT count(*) as ct FROM images WHERE draft = 0`);224 this._close();225 return rows[0];226 }227 async count_all_drafts () {228 this._connect();229 const rows = await this._run(`SELECT count(*) as ct FROM images WHERE draft = 1 AND content IS NOT NULL AND content <> ''`);230 this._close();231 return rows[0];232 }233 async count_all_new () {234 this._connect();235 const rows = await this._run(`SELECT count(*) as ct FROM images WHERE draft = 1 AND (content IS NULL OR content = '')`);236 this._close();237 return rows[0];238 }239 async count_all_by_tag (tag) {240 this._connect();241 const rows = await this._run(`SELECT count(*) as ct FROM images WHERE uuid IN (SELECT uuid FROM tags WHERE tag = ?) AND draft = 0`, [tag]);242 this._close();243 return rows[0];244 }245 async read_all (offset, limit) {246 if (offset === 'undefined') {247 offset = 0;248 }249 if (limit === 'undefined') {250 limit = 10;251 }252 this._connect();253 let results = await this._run(`SELECT * FROM images WHERE draft = 0 ORDER BY datetime(date_published) desc LIMIT ? OFFSET ?`, [limit, offset]);254 results = results.map(r => this._process_row(r));255 this._close();256 return results;257 }258 async read_all_by_tag (tag, offset, limit) {259 if (offset === 'undefined') {260 offset = 0;261 }262 if (limit === 'undefined') {263 limit = 10;264 }265 this._connect();266 let results = await this._run(`SELECT * FROM images WHERE uuid IN (SELECT uuid FROM tags WHERE tag = ?) AND draft = 0 ORDER BY datetime(date_published) desc LIMIT ? OFFSET ?`, [tag, limit, offset]);267 results = results.map(r => this._process_row(r));268 this._close();269 return results;270 }271 async read_all_drafts (offset, limit) {272 if (offset === 'undefined') {273 offset = 0;274 }275 if (limit === 'undefined') {276 limit = 10;277 }278 this._connect();279 let results = await this._run(`SELECT * FROM images WHERE draft = 1 AND content IS NOT NULL AND content <> '' ORDER BY datetime(date_updated) desc LIMIT ? OFFSET ?`, [limit, offset]);280 results = results.map(r => this._process_row(r));281 this._close();282 return results;283 }284 async read_all_new (offset, limit) {285 if (offset === 'undefined') {286 offset = 0;287 }288 if (limit === 'undefined') {289 limit = 10;290 }291 this._connect();292 let results = await this._run(`SELECT * FROM images WHERE draft = 1 AND (content IS NULL OR content = '') ORDER BY datetime(date_updated) desc LIMIT ? OFFSET ?`, [limit, offset]);293 results = results.map(r => this._process_row(r));294 this._close();295 return results;296 }297 async read (uuid) {298 this._connect();299 const results = await this._run(`SELECT * FROM images WHERE uuid = ?` , [uuid]);300 if (results.length > 0) {301 if (results.length > 1) {302 throw `Too many rows ${results.length} for UUID ${uuid}`;303 }304 return this._process_row(results[0]);305 }306 }307}308class Notes {309 310 constructor (folder) {311 this._fname = path.join(folder, _IMAGES_DB);312 }313 _connect () {314 this._db = new sqlite3.Database(this._fname);315 }316 _close () {317 if (this._db) {318 this._db.close();319 }320 }321 _run (sql, params) {322 // allow queries to be using asynchronously323 if (this._db) { 324 return new Promise((resolve, reject) => {325 this._db.all(sql, params, function (error, rows) {326 if (error)327 reject(error);328 else329 resolve(rows);330 });331 });332 }333 }334 async create (desc) {335 this._connect();336 const timestamp = toISO(new Date());337 let rows = await this._run(`SELECT * FROM notes WHERE uuid = ? LIMIT 1`, [desc.uuid])338 if (rows.length > 0) {339 throw `UUID ${desc.uuid} already exists`;340 }341 await this._run(`INSERT INTO notes VALUES (?, ?, ?)`, [342 desc.uuid,343 desc.content.join('\n\n'),344 timestamp345 ]);346 this._close();347 }348 async update (desc) {349 this._connect();350 const timestamp = toISO(new Date());351 let rows = await this._run(`SELECT * FROM notes WHERE uuid = ? LIMIT 1`, [desc.uuid]);352 if (rows.length > 0) {353 await this._run(`UPDATE notes SET content = ?, date_updated = ? WHERE uuid = ?`,354 [desc.content.join('\n\n'), timestamp, desc.uuid])355 }356 else { 357 await this._run(`INSERT INTO notes VALUES (?, ?, ?)`, [358 desc.uuid,359 desc.content.join('\n\n'),360 timestamp361 ]);362 }363 this._close();364 }365 async delete (uuid) {366 this._connect();367 await this._run(`DELETE FROM notes WHERE uuid = ?`, [uuid]);368 this._close();369 }370 _process_row (r) {371 return {372 uuid: r.uuid,373 content: r.content.split('\n\n'),374 date_updated: new Date(r.date_updated)375 }376 }377 async count_all () {378 this._connect();379 const rows = await this._run(`SELECT count(*) as ct FROM notes`);380 this._close();381 return rows[0];382 }383 async read_all (offset, limit) {384 if (offset === 'undefined') {385 offset = 0;386 }387 if (limit === 'undefined') {388 limit = 10;389 }390 this._connect();391 let results = await this._run(`SELECT * FROM notes ORDER BY datetime(date_updated) desc LIMIT ? OFFSET ?`, [limit, offset]);392 results = results.map(r => this._process_row(r));393 this._close();394 return results;395 }396 async read (uuid) {397 this._connect();398 const results = await this._run(`SELECT * FROM notes WHERE uuid = ?` , [uuid]);399 if (results.length > 0) {400 if (results.length > 1) {401 throw `Too many rows ${results.length} for UUID ${uuid}`;402 }403 return this._process_row(results[0]);404 }405 }406}407module.exports = {408 Version: Version,409 Tags: Tags,410 Images: Images,411 Notes: Notes,...

Full Screen

Full Screen

mongoClient.js

Source:mongoClient.js Github

copy

Full Screen

1"use strict"2var {MongoClient,ObjectID} = require('mongodb');3var assert = require('assert');4var log4js = require('log4js');5var logger = log4js.getLogger();6class MongoDb {7 constructor(host, port, db, user, pw){8 return new Promise((done, fail) => {9 var auth = (user && pw) ? (user+':'+pw+'@') : '';10 port = port || 27017;11 MongoClient.connect(`mongodb://${auth}${host}:${port}/${db}`, (err, db) => {12 assert.equal(null, err);13 this._connect = db;14 done(this);15 })16 });17 }18 convQuery(query){19 try{20 if(query.hasOwnProperty('_id')){21 if(query['_id']['$in']){22 query['_id']['$in'] = query['_id']['$in'].map((tId) => ObjectID(tId));23 }else{24 query['_id'] = ObjectID(query['_id']);25 }26 }27 }catch(e){28 logger.error(e.message);29 }30 return query;31 }32 insert(collect, doc, options){33 return new Promise((done, fail) => {34 if(this._connect && doc){35 var coll = this._connect.collection(collect);36 coll[(Array.isArray(doc) ? 'insertMany' : 'insert')](doc, options, (err, info) => {37 err && logger.error(err)38 assert.equal(null, err);39 //logger.info(result);40 done(info);41 });42 }else{43 fail();44 }45 });46 }47 remove(collect, query, options){48 return new Promise((done, fail) => {49 if(this._connect && query){50 var coll = this._connect.collection(collect);51 var ret = coll.removeMany(query, options);52 // conver object id53 this.convQuery(query);54 55 done();56 }else{57 fail();58 }59 });60 }61 findAndModify(collect, query, doc, options){62 return new Promise((done, fail) => {63 if(this._connect && query && doc){64 var coll = this._connect.collection(collect);65 //this.convQuery(query);66 options = options || {};67 coll.findOneAndUpdate(query, doc, options).then((data) => {68 done(data);69 }).catch((e) => {70 fail(e);71 });72 }else{73 fail();74 }75 });76 }77 upSert(collect, query, doc, options){78 return new Promise((done, fail) => {79 if(this._connect && doc){80 var coll = this._connect.collection(collect);81 // conver object id82 this.convQuery(query);83 84 options = options || {};85 options.w = 1;86 options.upsert = true;87 88 coll[(Array.isArray(doc) ? 'updateMany' : 'update')](query, doc,options, (err, info) => {89 err && logger.error(err)90 assert.equal(null, err);91 done(info);92 });93 }else{94 fail();95 }96 })97 }98 query(collect, query, options){99 //logger.info('test')100 return new Promise((done, fail) => {101 if(this._connect){102 var coll = this._connect.collection(collect);103 // conver object id104 this.convQuery(query);105 106 //logger.info(coll);107 coll.find(query, options).toArray((err, info) => {108 assert.equal(null, err);109 done(info);110 });111 }else{112 fail();113 }114 });115 }116 buildIndex(collect, keys, reserve, extras){117 return new Promise((done, fail) => {118 if(this._connect){119 var coll = this._connect.collection(collect);120 var index = {};121 Array.isArray(keys) ? keys.map((key) => {index[key]= (reserve ? -1 : 1)}) : (index[keys]=(reserve ? -1 : 1));122 return callback ? coll.ensureIndex(index, extras, (err, indexName) => {123 assert.equal(null, err);124 console.log('buildIndex:'+indexName)125 done(indexName);126 }) : coll.ensureIndex(index, extras);127 }else{128 fail();129 }130 });131 }132 update(collect, query, doc){133 return new Promise((done, fail) => {134 if(this._connect){135 // conver object id136 this.convQuery(query);137 var coll = this._connect.collection(collect);138 return coll.updateOne(query, doc, {w:1}).then((info) => {139 done(info);140 }).catch((e) => {141 fail(e)142 });143 }else{144 fail();145 }146 });147 }148 checkIndex(collect, option){149 return new Promise((done, fail) => {150 if(this._connect){151 var coll = this._connect.collection(collect);152 return coll.indexInformation(option || {full:true}, (err, info) => {153 assert.equal(null, err);154 done(info);155 });156 }else{157 fail();158 }159 });160 }161}...

Full Screen

Full Screen

cardinfo.js

Source:cardinfo.js Github

copy

Full Screen

1 /******************************************************************************************************************* 2 Ä«µåÇҺΠ¾È³»3 *******************************************************************************************************************/4 $( document ).ready(function() {5 $('[cardinfo]').click(function(e) {6 $('#sp-cardinfo, #sp-cardinfo-loading').remove();7 var _url = $(this).data('url');8 var _offset = $(this).offset();9 var _load = '<div id="sp-cardinfo-loading" style="top:'+ (_offset.top-24) +'px;left:'+ (_offset.left-7) +'px;">ºÒ·¯¿À´ÂÁß</div>';10 var _now = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;11 $('body').prepend( _load );12 $('#sp-cardinfo-loading').fadeIn('fast');13 $.ajax({14 type: 'get',15 dataType: 'html',16 url: _url,17 success: function(data){18 var $result = $(data).filter('#sp-result').html();19 $('body').append( $result );20 $('#sp-cardinfo').css('height',$(document).height()).fadeIn('fast');21 //$('#sp-cardinfo > ul').css({'top':_offset.top,'left':_offset.left - 600});22 $('#sp-cardinfo > ul').css('top',_now + 100);23 $('#sp-cardinfo-loading').fadeOut();24 /* ¿¬µ¿ */25 var _connect;26 var _connectdata;27 if( $('#sp-cardinfo [connect="¹«ÀÌÀÚÇÒºÎ"]').size() ){28 $('#sp-cardinfo [connect="¹«ÀÌÀÚÇÒºÎ"]').each(function( a ){29 if( $(this).data('connect') ){30 _connectdata = $(this).data('connect').split('^');31 if( _connectdata.length == 1 ){32 _connect = '';33 _connect += '<ul>';34 _connect += ' <p>'+ _connectdata[0] +'</p>';35 _connect += '</ul>';36 $('#sp-cardinfo [connectbox="¹«ÀÌÀÚÇÒºÎ"]').append( _connect );37 }else if( _connectdata.length == 2 ){38 _connect = '';39 _connect += '<ul>';40 _connect += ' <li class="sp-title">'+ _connectdata[0] +'</li>';41 _connect += ' <li class="sp-content">'+ _connectdata[1] +'</li>';42 _connect += '</ul>';43 $('#sp-cardinfo [connectbox="¹«ÀÌÀÚÇÒºÎ"]').append( _connect );44 }45 }46 });47 }48 if( $('#sp-cardinfo [connect="ºÎºÐ¹«ÀÌÀÚÇÒºÎ"]').size() ){49 $('#sp-cardinfo [connect="ºÎºÐ¹«ÀÌÀÚÇÒºÎ"]').each(function( a ){50 if( $(this).data('connect') ){51 _connectdata = $(this).data('connect').split('^');52 if( _connectdata.length == 1 ){53 _connect = '';54 _connect += '<ul>';55 _connect += ' <p>'+ _connectdata[0] +'</p>';56 _connect += '</ul>';57 $('#sp-cardinfo [connectbox="ºÎºÐ¹«ÀÌÀÚÇÒºÎ"]').append( _connect );58 }else if( _connectdata.length == 2 ){59 _connect = '';60 _connect += '<ul>';61 _connect += ' <li class="sp-title">'+ _connectdata[0] +'</li>';62 _connect += ' <li class="sp-content">'+ _connectdata[1] +'</li>';63 _connect += '</ul>';64 $('#sp-cardinfo [connectbox="ºÎºÐ¹«ÀÌÀÚÇÒºÎ"]').append( _connect );65 }66 }67 });68 }69 },70 error: function(xhr,status,error){71 $('#sp-cardinfo-loading').html('Àá½Ã ÈÄ ´Ù½Ã ½ÃµµÇØÁÖ¼¼¿ä');72 setTimeout(function(){73 $('#sp-cardinfo-loading').fadeOut('fast');74 }, 2000);75 },76 timeout: 300077 });78 });79 //KEY EVENT80 $(document).keydown(function(e) {81 if (e.keyCode == 27) {82 $('#sp-cardinfo').fadeOut('fast');83 }84 });85 //$(document).on('click', '#sp-cardinfo, #sp-cardinfo > ul > button', function(e) {86 $('#sp-cardinfo, #sp-cardinfo > ul > button').live('click', function(){87 $('#sp-cardinfo').fadeOut('fast');88 });89 //$(document).on('click', ''#sp-cardinfo > ul', function(e) {90 $('#sp-cardinfo > ul').live('click', function(e){91 e.stopPropagation();92 });93 //$(document).on('click', '#sp-cardinfo > ul > p > button', function(e) {94 $('#sp-cardinfo > ul > p > button').live('click',function(){95 var _index = $('#sp-cardinfo > ul > p > button').index( $(this) );96 $('#sp-cardinfo > ul > p > button').removeClass('-on');97 $('#sp-cardinfo > ul > p > button').eq(_index).addClass('-on');98 $('#sp-cardinfo > ul > li').removeClass('-on');99 $('#sp-cardinfo > ul > li').eq(_index).addClass('-on');100 });...

Full Screen

Full Screen

service.test.js

Source:service.test.js Github

copy

Full Screen

1/*global bridge,assert,suite,setup,teardown,test*/2/*jshint esnext:true, maxlen:false*/3suite('Service /', function() {4 var service = bridge.service;5 setup(function() {6 this.sinon = sinon.sandbox.create();7 });8 teardown(function() {9 this.sinon.restore();10 });11 suite('Service#method()', function() {12 var fakeMessage;13 var myService;14 setup(function() {15 myService = service('service-name');16 fakeMessage = {17 type: '_method',18 foo: 'foo',19 data: {20 name: 'my-method',21 args: ['a', 'b', 'c']22 },23 event: { ports: [] },24 respond: sinon.spy()25 };26 });27 teardown(function() {28 myService.destroy();29 });30 test('it responds to the message with the return value', function() {31 myService.method('my-method', () => 'value');32 myService.emit('_method', fakeMessage);33 sinon.assert.calledWith(fakeMessage.respond, 'value');34 });35 test('it applys arguments to the callback', function() {36 var spy = sinon.spy();37 myService.method('my-method', spy);38 myService.emit('_method', fakeMessage);39 sinon.assert.calledWith(spy, 'a', 'b', 'c');40 });41 test('it throws if no method is found', function(done) {42 myService.method('my-method', () => {});43 fakeMessage.data.name = 'unknown';44 try { myService.emit('_method', fakeMessage); }45 catch (e) { done(); }46 });47 });48 suite('on connect', function() {49 var fakeMessage;50 setup(function() {51 fakeMessage = {52 type: '_connect',53 data: {54 clientId: 123,55 service: 'service1'56 },57 event: { ports: [] },58 setSourcePort: sinon.spy(),59 respond: sinon.spy()60 };61 });62 teardown(function() {});63 test('it does not respond if the service name does not match', function() {64 fakeMessage.data.service = 'service3';65 var myService = service('service1');66 myService.emit('_connect', fakeMessage);67 sinon.assert.notCalled(fakeMessage.respond);68 myService = service('service2');69 myService.emit('_connect', fakeMessage);70 sinon.assert.notCalled(fakeMessage.respond);71 myService = service('service3');72 myService.emit('_connect', fakeMessage);73 sinon.assert.called(fakeMessage.respond);74 });75 test('it does not respond if no clientId was provided', function() {76 delete fakeMessage.data.clientId;77 var myService = service('service1');78 myService.emit('_connect', fakeMessage);79 sinon.assert.notCalled(fakeMessage.respond);80 fakeMessage.data.clientId = 123;81 myService.emit('_connect', fakeMessage);82 sinon.assert.called(fakeMessage.respond);83 });84 test('it does not respond if the client is already connected', function() {85 var myService = service('service1');86 myService.emit('_connect', fakeMessage);87 sinon.assert.called(fakeMessage.respond);88 fakeMessage.respond.reset();89 myService.emit('_connect', fakeMessage);90 sinon.assert.notCalled(fakeMessage.respond);91 });92 test('it responds on MessageChannel the Client and Service are not within Windows', function() {93 var service = bridge.service('service1');94 var port = new MessageChannel().port1;95 fakeMessage.event.ports = [port];96 // Client 197 fakeMessage.data.originEnv = 'Window';98 service.emit('_connect', fakeMessage);99 sinon.assert.notCalled(fakeMessage.setSourcePort);100 // Client 2101 fakeMessage.data.clientId = 1234;102 fakeMessage.data.originEnv = 'Worker';103 service.emit('_connect', fakeMessage);104 sinon.assert.calledWith(fakeMessage.setSourcePort, port);105 });106 });...

Full Screen

Full Screen

db.js

Source:db.js Github

copy

Full Screen

1const mongodb = require("mongodb");2const mongoClient = mongodb.MongoClient;3// 以下划线开头的,一般都是做为私有的来定义的。4function _connect(cb) {5 mongoClient.connect("mongodb://127.0.0.1:27017",{useUnifiedTopology:true},function (err,client) {6 if(err)7 console.log("网络连接错误");8 else{9 // console.log("成功");10 const db = client.db("lwy");11 cb(db)12 }13 })14}15// 插入一条记录16// coll:集合17// insertObj:插入的内容18// cb 插入成功以后的回调函数,用于返回结果19module.exports.insertOne = function (coll,insertObj,cb) {20 _connect(function (db) {21 db.collection(coll).insertOne(insertObj,cb)22 // db.collection(coll).insertOne(insertObj,function (err,results) {23 // cb(err,results);24 // })25 })26}27/*28* 根据条件,获得总文档数29* coll:指定集合30* whereObj:条件*/31module.exports.count = function (coll,whereObj,cb) {32 _connect(function (db) {33 db.collection(coll).countDocuments(whereObj,cb)34 })35}36module.exports.connect = _connect;37/*根据ID进行删除*/38module.exports.deleteOneById = function (coll,id,cb) {39 _connect(function (db) {40 db.collection(coll).deleteOne({41 _id:mongodb.ObjectId(id)42 },cb)43 })44}45/*根据ID进行修改*/46module.exports.updateOneById = function (coll,id,upObj,cb) {47 _connect(function (db) {48 db.collection(coll).updateOne({49 _id:mongodb.ObjectId(id)50 },upObj,cb)51 })52}53// 根据条件更改多条记录54module.exports.updateMany = function (coll,whereObj,upObj,cb) {55 _connect(function (db) {56 db.collection(coll).updateMany(whereObj,upObj,cb)57 })58}59module.exports.updateOne = function (coll,whereObj,upObj,cb) {60 _connect(function (db) {61 db.collection(coll).updateOne(whereObj,upObj,cb)62 })63}64// 根据ID获得相对应的信息65module.exports.findOneById = function (coll,id,cb) {66 _connect(function (db) {67 db.collection(coll).findOne({68 _id:mongodb.ObjectId(id)69 },cb)70 })71}72module.exports.findOne = function (coll,obj,cb) {73 _connect(function (db) {74 db.collection(coll).findOne(obj.whereObj,{projection: obj.getObj},cb)75 })76}77// 根据条件进行查找78module.exports.find = function (coll,obj,cb) {79 obj.whereObj = obj.whereObj || {};80 obj.getObj = obj.getObj || {};81 obj.sortObj = obj.sortObj || {};82 obj.skip = obj.skip || 0;83 obj.limit = obj.limit || 0;84 // console.log(obj)85 _connect(function (db) {86 db.collection(coll)87 .find(obj.whereObj)88 .project(obj.getObj)//通过0/1返回指定字段 0与1不可混用89 .skip(obj.skip)90 .limit(obj.limit)91 .sort(obj.sortObj)92 .toArray(cb)93 })94}95//查找字段去重96module.exports.distinct = function (coll,obj,cb) {97 obj.getObj = obj.getObj || {};98 _connect(function (db) {99 db.collection(coll)100 .distinct(obj.getObj)101 .then(cb)102 })103}104module.exports.connect = _connect;105// _connect(function (db) {106// console.log(db)...

Full Screen

Full Screen

bankmiss.js

Source:bankmiss.js Github

copy

Full Screen

1 /******************************************************************************************************************* 2 미확인 입금자3 *******************************************************************************************************************/4 $( document ).ready(function() {5 $('[bankmiss]').click(function(e) {6 $('#sp-bankmiss, #sp-bankmiss-loading').remove();7 var _url = $(this).data('url');8 var _offset = $(this).offset();9 var _load = '<div id="sp-bankmiss-loading" style="top:'+ (_offset.top-24) +'px;left:'+ (_offset.left-7) +'px;">불러오는중</div>';10 var _now = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;11 $('body').prepend( _load );12 $('#sp-bankmiss-loading').fadeIn('fast');13 $.ajax({14 type: 'get',15 dataType: 'html',16 url: _url,17 success: function(data){18 var $result = $(data).filter('#sp-result').html();19 $('body').append( $result );20 $('#sp-bankmiss').css('height',$(document).height()).fadeIn('fast');21 //$('#sp-bankmiss .sp-bankmiss-inside').css('marginTop',_offset.top);22 $('#sp-bankmiss .sp-bankmiss-inside').css('top',_now + 100);23 $('#sp-bankmiss-loading').fadeOut();24 /* 연동 */25 var _connect;26 var _connectdata;27 if( $('#sp-bankmiss [connect="미확인입금자"]').size() ){28 $('#sp-bankmiss [connect="미확인입금자"]').each(function( a ){29 if( $(this).data('connect') ){30 _connectdata = $(this).data('connect').split('^');31 if( _connectdata.length == 4 ){32 _connect = '';33 _connect += '<tr>';34 _connect += ' <td>'+ _connectdata[0] +'</td>';35 _connect += ' <td>'+ _connectdata[1] +'</td>';36 _connect += ' <td>'+ _connectdata[2] +'</td>';37 _connect += ' <td>'+ _connectdata[3] +'</td>';38 _connect += '</tr>';39 $('#sp-bankmiss [connectbox]').append( _connect );40 }41 }42 });43 }44 },45 error: function(xhr,status,error){46 $('#sp-bankmiss-loading').html('잠시 후 다시 시도해주세요');47 setTimeout(function(){48 $('#sp-bankmiss-loading').fadeOut('fast');49 }, 2000);50 },51 timeout: 300052 });53 });54 //KEY EVENT55 $(document).keydown(function(e) {56 if (e.keyCode == 27) {57 $('#sp-bankmiss').fadeOut('fast');58 }59 });60 //$(document).on('click', '#sp-bankmiss, #sp-bankmiss button', function(e) {61 $('#sp-bankmiss, #sp-bankmiss button').live('click', function(){62 $('#sp-bankmiss').fadeOut('fast');63 });64 //$(document).on('click', '#sp-bankmiss .sp-bankmiss-inside', function(e) {65 $('#sp-bankmiss .sp-bankmiss-inside').live('click', function(e){66 e.stopPropagation();67 });...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

1var connect = require('express')2 //, gzip = require('connect-gzip')3 , bodyParser = require('body-parser')4 , cookieParser = require('cookie-parser')5 , serveStatic = require('serve-static')6 , compose = require('./util/compose')7 , parse = require('url').parse8var Application = module.exports = function Application(options) {9 if (!(this instanceof Application)) 10 return new Application()11 this._connect = connect(options)12 //this._connect.use(gzip.gzip())13 this._stack = []14}15var app = Application.prototype16app.serve = function serve(directory, options) {17 var mountPath18 19 if(options && options.mount) {20 mountPath = options.mount21 delete options.mount22 this._connect.use(mountPath, serveStatic(directory, options))23 } else {24 this._connect.use(serveStatic(directory, options))25 }26 return this27}28app.connect = function connect(fn) {29 if(!this._defaults) {30 this._defaults = true31 this._connect.use(cookieParser())32 this._connect.use(bodyParser.urlencoded({ extended:true }))33 }34 if(this._stack.length) {35 throw new Error('All connect middleware (.connect) must be added before any kent middleware (.use)')36 }37 38 this._connect.use(fn)39 return this40}41app.set = function set() {42 this._connect.set.apply(this._connect, arguments)43 return this44}45app.use = function use(fn) {46 if(fn._stack) this._stack.push.apply(this._stack, fn._stack)47 else this._stack.push(fn)48 return this49}50app.listen = function listen() {51 var fn = compose(this._stack)52 this._connect.use(function(req, res, next) {53 fn.call(createContext(req, res), next)()54 })55 return this._connect.listen.apply(this._connect, arguments)56}57function createContext(req, res) {58 var ctx = {59 req,60 res,61 body:req.body,62 cookies:{63 get:function(name) { return req.cookies[name] },64 set:function(name, value, options) { res.cookie(name, value, options) }65 },66 redirect:function(url) {67 res.writeHead(302, { Location:url })68 res.end()69 },70 params:{}71 }72 var parsedUrl = parse(req.url, true)73 ctx.url = parsedUrl.path74 ctx.path = parsedUrl.pathname75 ctx.query = parsedUrl.query76 ctx.host = req.headers.host77 ctx.site = req.protocol+'://'+ctx.host78 ctx.href = ctx.site+parsedUrl.path79 return ctx...

Full Screen

Full Screen

grid.js

Source:grid.js Github

copy

Full Screen

...27 addEdges() {28 for (let col = 0; col < this.size; col++) {29 for (let row = 0; row < this.size; row++) {30 const current = this._cellId(col, row)31 this._connect(current, col + 1, row) // right32 this._connect(current, col - 1, row) // left33 this._connect(current, col, row + 1) // bottom34 this._connect(current, col, row - 1) // top35 this._connect(current, col + 1, row + 1) // bottom-right36 this._connect(current, col + 1, row - 1) // top-right 37 this._connect(current, col - 1, row + 1) // bottom-left38 this._connect(current, col - 1, row - 1) // top-left39 }40 }41 }42 _cellId(y, x) {43 const startingIndex = 6544 const letter = String.fromCharCode(y + startingIndex)45 return `${letter}${x}`46 }47 _connect(node, y, x) {48 this.graph.connect(node, this._cellId(y, x))49 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const context = await browser.newContext();4 const page = await context.newPage();5 await page.screenshot({ path: 'example.png' });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browserServer = await chromium._launchServer({ headless: false });11 console.log(browserServer.wsEndpoint());

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _connect } = require('playwright/lib/client/connection.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await _connect({5 });6 const page = await browser.newPage();7 await page.goto('

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { _connect } = require('playwright/lib/server/browserType');3const { BrowserType } = require('playwright/lib/server/browserType');4const { Browser } = require('playwright/lib/server/browser');5async function main() {6 const browserType = new BrowserType('chromium', playwright.chromium);7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.screenshot({ path: 'example.png' });10 await browser.close();11}12main();13Hi, I am trying to use the _connect method of playwright in my project. I am able to connect to the browser and create a context and page. But I am not able to use the methods of the page. For example, I am not able to use the page.goto() method. I am getting the following error:14at ProgressController.run (/Users/abhaygupta/Projects/screencast/node_modules/playwright/lib/utils/progress.js:97:23)15at async Page.goto (/Users/abhaygupta/Projects/screencast/node_modules/playwright/lib/server/page.js:1058:29)16at async main (/Users/abhaygupta/Projects/screencast/test.js:13:5)17const playwright = require('playwright');18const { _connect } =

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _connect } = require('playwright/lib/client/connection');2const { Playwright } = require('playwright/lib/client/playwright');3(async () => {4 const playwright = new Playwright();5 const browserServer = await playwright.chromium.launchServer();6 const transport = await _connect({7 wsEndpoint: browserServer.wsEndpoint(),8 });9 const browser = await playwright.chromium.connect({ transport });10 const page = await browser.newPage();11 await page.screenshot({ path: 'example.png' });12 await browser.close();13 await browserServer.close();14})();15const { _connect } = require('playwright/lib/client/connection');16const { Playwright } = require('playwright/lib/client/playwright');17(async () => {18 const playwright = new Playwright();19 const browserServer = await playwright.chromium.launchServer();20 const transport = await _connect({21 wsEndpoint: browserServer.wsEndpoint(),22 });23 const browser = await playwright.chromium.connect({ transport });24 const page = await browser.newPage();25 await page.screenshot({ path: 'example.png' });26 await browser.close();27 await browserServer.close();28})();29const { _connect } = require('playwright/lib/client/connection');30const { Playwright } = require('playwright/lib/client/playwright');31(async () => {32 const playwright = new Playwright();33 const browserServer = await playwright.chromium.launchServer();34 const transport = await _connect({35 wsEndpoint: browserServer.wsEndpoint(),36 });37 const browser = await playwright.chromium.connect({ transport });38 const page = await browser.newPage();39 await page.screenshot({ path: 'example.png' });40 await browser.close();41 await browserServer.close();42})();43const { _connect } = require('playwright/lib

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { _connect } = require('playwright/lib/server/chromium');3const browser = await _connect({4 });5const context = await browser.newContext();6const page = await context.newPage();7const { connect } = require('playwright');8const browser = await connect({9 });10const context = await browser.newContext();11const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _connect } = require('playwright/lib/server/chromium');2const { BrowserContext } = require('playwright/lib/server/browserContext');3const browser = await _connect({ wsEndpoint });4const context = await browser.newContext();5const { _createContext } = require('playwright/lib/server/chromium');6const { BrowserContext } = require('playwright/lib/server/browserContext');7const browser = await chromium.launch();8const context = await _createContext(browser, {});9const { _createBrowser } = require('playwright/lib/server/chromium');10const { Browser } = require('playwright/lib/server/browser');11const browser = await _createBrowser('chromium', {});12const { _createBrowserServer } = require('playwright/lib/server/chromium');13const { BrowserServer } = require('playwright/lib/server/browserServer');14const browserServer = await _createBrowserServer('chromium', {});15const { _createBrowserFetcher } = require('playwright/lib/server/chromium');16const { BrowserFetcher } = require('playwright/lib/server/browserFetcher');17const browserFetcher = await _createBrowserFetcher('chromium', {});18const { _createBrowserType } = require('playwright/lib/server/chromium');19const { BrowserType } = require('playwright/lib/server/browserType');20const browserType = await _createBrowserType('chromium', {});21const { _createBrowserContext } = require

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _connect } = require("playwright");2const browser = await _connect({3});4const page = await browser.newPage();5await page.screenshot({ path: "google.png" });6await browser.close();7const playwright = require("playwright");8const http = require("http");9const fs = require("fs");10const path = require("path");11const { promisify } = require("util");12const readFile = promisify(fs.readFile);13const writeFile = promisify(fs.writeFile);14const server = http.createServer(async (req, res) => {15 if (req.url === "/playwright") {16 const playwrightServer = await playwright._connectToServer({17 });18 const browser = await playwrightServer.chromium.launch();19 const page = await browser.newPage();20 const screenshot = await page.screenshot();21 await writeFile(path.join(__dirname, "google.png"), screenshot);22 await browser.close();23 await playwrightServer.close();24 res.writeHead(200, { "Content-Type": "image/png" });25 res.end(screenshot);26 } else {27 const client = await readFile(path.join(__dirname, "test.js"));28 res.writeHead(200, { "Content-Type": "text/javascript" });29 res.end(client);30 }31});32server.listen(3000, "localhost", () => {33});34module.exports = {35 webServer: {36 },37};38{39 "scripts": {

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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