How to use channelName method in wpt

Best JavaScript code snippet using wpt

app.js

Source:app.js Github

copy

Full Screen

1/**2 * Copyright 2017 IBM All Rights Reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the 'License');5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 * See the License for the specific language governing permissions and13 * limitations under the License.14 */15'use strict';16var fs = require('fs');17var logger = require('./config/winston.js');18var express = require('express');19var bodyParser = require('body-parser');20var http = require('http');21var util = require('util');22var app = express();23var expressJWT = require('express-jwt');24var jwt = require('jsonwebtoken');25var bearerToken = require('express-bearer-token');26var cors = require('cors');27require('./config.js');28var hfc = require('fabric-client');29var helper = require('./app/helper.js');30var install = require('./app/install-chaincode.js');31var instantiate = require('./app/instantiate-chaincode.js');32var invoke = require('./app/invoke-transaction.js');33var query = require('./app/query.js');34var shell = require('shelljs');35var mkdirp = require('mkdirp');36var host = process.env.HOST || hfc.getConfigSetting('host');37var port = process.env.PORT || hfc.getConfigSetting('port');38///////////////////////////////////////////////////////////////////////////////39//////////////////////////////// SET CONFIGURATONS ////////////////////////////40///////////////////////////////////////////////////////////////////////////////41app.options('*', cors());42app.use(cors());43app.use(bodyParser.json());44app.set('secret', hfc.getConfigSetting('secret'));45app.get('/networkHealth', async function (req, res) {46 logger.info('<<<<<<<<<<<<<<<<< G E T N E T W O R K H E A L T H W I T H S C R I P T >>>>>>>>>>>>>>>>>');47 logger.debug('End point : /networkHealth');48 shell.exec('cd ../.. ; ./network_health.sh', function (code, stdout, stderr) {49 console.log('Exit code:', code);50 console.log('Program output:', stdout);51 console.log('Program stderr:', stderr);52 res.status(200).send(JSON.parse(stdout));53 });54});55app.use(expressJWT({56 secret: app.get('secret')57}).unless({58 path: ['/users/register']59}));60app.use(bearerToken());61app.use(function (req, res, next) {62 logger.debug(' ------>>>>>> new request for %s', req.originalUrl);63 if (req.originalUrl.indexOf('/users/register') >= 0) {64 return next();65 }66 if (req.name === 'UnauthorizedError') {67 res.status(error.status).send({ message: error.message });68 logger.error(error);69 }70 var token = req.token;71 jwt.verify(token, app.get('secret'), function (err, decoded) {72 if (err) {73 res.status(403).send({74 success: false,75 message: 'Failed to authenticate token.'76 });77 return;78 } else {79 req.username = decoded.username;80 req.orgname = decoded.orgName;81 logger.debug(util.format('Decoded from JWT token: username - %s, orgname - %s', decoded.username, decoded.orgName));82 return next();83 }84 });85});86///////////////////////////////////////////////////////////////////////////////87//////////////////////////////// START SERVER /////////////////////////////////88///////////////////////////////////////////////////////////////////////////////89var server = http.createServer(app).listen(port, function () { });90logger.info('****************** SERVER STARTED ************************');91logger.info('*************** http://%s:%s ******************', host, port);92server.timeout = 240000;93function getErrorMessage(field) {94 var response = {95 success: false,96 message: field + ' field is missing or Invalid in the request'97 };98 return response;99}100///////////////////////////////////////////////////////////////////////////////101///////////////////////// REST ENDPOINTS START HERE ///////////////////////////102///////////////////////////////////////////////////////////////////////////////103// Register and enrol user 104app.post('/users/register', async function (req, res) {105 var username = req.body.username;106 var orgName = req.body.orgName;107 var role = req.body.role;108 var attrs = req.body.attrs;109 var secret = req.body.secret;110 logger.debug('User name : ' + username);111 logger.debug('Org name : ' + orgName);112 logger.debug('Role : ' + role);113 logger.debug('Attrs : ' + attrs);114 logger.debug('Secret : ' + secret);115 if (!username) {116 res.status(400).json(getErrorMessage('\'username\''));117 return;118 }119 if (!orgName) {120 res.status(400).json(getErrorMessage('\'orgName\''));121 return;122 }123 if (!secret) {124 res.status(400).json(getErrorMessage('\'secret\''));125 return;126 }127 let secret2 = await helper.checkSecret(orgName, secret)128 if (secret === secret2) {129 var token = jwt.sign({130 exp: Math.floor(Date.now() / 1000) + parseInt(hfc.getConfigSetting('jwt_expiretime')),131 username: username,132 orgName: orgName,133 }, app.get('secret'));134 let response = await helper.registerUser(username, orgName, role, attrs);135 if (response && typeof response !== 'string') {136 response.token = token;137 res.status(200).send(response);138 } else {139 res.status(400).json({ success: false, message: response });140 }141 }142 else {143 res.status(400).json({ success: false, message: 'Invalid organization secret' });144 }145});146// Install chaincode on target peers147app.post('/chaincodes', async function (req, res) {148 logger.debug('==================== INSTALL CHAINCODE ==================');149 var peers = req.body.peers;150 var chaincodeName = req.body.chaincodeName;151 var chaincodePath = req.body.chaincodePath;152 var chaincodeVersion = req.body.chaincodeVersion;153 var chaincodeType = req.body.chaincodeType;154 logger.debug('peers : ' + peers); // target peers list155 logger.debug('chaincodeName : ' + chaincodeName);156 logger.debug('chaincodePath : ' + chaincodePath);157 logger.debug('chaincodeVersion : ' + chaincodeVersion);158 logger.debug('chaincodeType : ' + chaincodeType);159 if (!peers || peers.length == 0) {160 res.status(400).json(getErrorMessage('\'peers\''));161 return;162 }163 if (!chaincodeName) {164 res.status(400).json(getErrorMessage('\'chaincodeName\''));165 return;166 }167 if (!chaincodePath) {168 res.status(400).json(getErrorMessage('\'chaincodePath\''));169 return;170 }171 if (!chaincodeVersion) {172 res.status(400).json(getErrorMessage('\'chaincodeVersion\''));173 return;174 }175 if (!chaincodeType) {176 res.status(400).json(getErrorMessage('\'chaincodeType\''));177 return;178 }179 let message = await install.installChaincode(peers, chaincodeName, chaincodePath, chaincodeVersion, chaincodeType, req.username, req.orgname)180 res.status(200).send(message);181});182// Instantiate chaincode on target peers183app.post('/channels/:channelName/chaincodes', async function (req, res) {184 logger.debug('==================== INSTANTIATE CHAINCODE ==================');185 var peers = req.body.peers;186 var chaincodeName = req.body.chaincodeName;187 var chaincodeVersion = req.body.chaincodeVersion;188 var channelName = req.params.channelName;189 var chaincodeType = req.body.chaincodeType;190 var fcn = req.body.fcn;191 var args = req.body.args;192 var policy = req.body.policy;193 logger.debug('peers : ' + peers);194 logger.debug('channelName : ' + channelName);195 logger.debug('chaincodeName : ' + chaincodeName);196 logger.debug('chaincodeVersion : ' + chaincodeVersion);197 logger.debug('chaincodeType : ' + chaincodeType);198 logger.debug('fcn : ' + fcn);199 logger.debug('args : ' + args);200 logger.debug('policy : ' + policy);201 if (!chaincodeName) {202 res.status(400).json(getErrorMessage('\'chaincodeName\''));203 return;204 }205 if (!chaincodeVersion) {206 res.status(400).json(getErrorMessage('\'chaincodeVersion\''));207 return;208 }209 if (!channelName) {210 res.status(400).json(getErrorMessage('\'channelName\''));211 return;212 }213 if (!chaincodeType) {214 res.status(400).json(getErrorMessage('\'chaincodeType\''));215 return;216 }217 if (!args) {218 res.status(400).json(getErrorMessage('\'args\''));219 return;220 }221 if (!policy) {222 res.status(400).json(getErrorMessage('\'policy\''));223 return;224 }225 let message = await instantiate.instantiateChaincode(peers, channelName, chaincodeName, chaincodeVersion, chaincodeType, fcn, args, req.username, req.orgname, policy);226 res.status(200).send(message);227});228// Invoke transaction on chaincode on target peers229app.post('/channels/:channelName/chaincodes/:chaincodeName', async function (req, res) {230 logger.debug('==================== INVOKE ON CHAINCODE ==================');231 var peers = req.body.peers;232 var chaincodeName = req.params.chaincodeName;233 var channelName = req.params.channelName;234 var fcn = req.body.fcn;235 var args = req.body.args;236 logger.debug('channelName : ' + channelName);237 logger.debug('chaincodeName : ' + chaincodeName);238 logger.debug('fcn : ' + fcn);239 logger.debug('args : ' + args);240 if (!chaincodeName) {241 res.status(400).json(getErrorMessage('\'chaincodeName\''));242 return;243 }244 if (!channelName) {245 res.status(400).json(getErrorMessage('\'channelName\''));246 return;247 }248 if (!fcn) {249 res.status(400).json(getErrorMessage('\'fcn\''));250 return;251 }252 if (!args) {253 res.status(400).json(getErrorMessage('\'args\''));254 return;255 }256 let message = await invoke.invokeChaincode(peers, channelName, chaincodeName, fcn, args, req.username, req.orgname);257 res.status(200).send(message);258});259// Query on chaincode on target peers260app.get('/channels/:channelName/chaincodes/:chaincodeName', async function (req, res) {261 logger.debug('==================== QUERY BY CHAINCODE ==================');262 var channelName = req.params.channelName;263 var chaincodeName = req.params.chaincodeName;264 let args = req.query.args;265 let fcn = req.query.fcn;266 let peer = req.query.peer;267 logger.debug('channelName : ' + channelName);268 logger.debug('chaincodeName : ' + chaincodeName);269 logger.debug('fcn : ' + fcn);270 logger.debug('args : ' + args);271 if (!chaincodeName) {272 res.status(400).json(getErrorMessage('\'chaincodeName\''));273 return;274 }275 if (!channelName) {276 res.status(400).json(getErrorMessage('\'channelName\''));277 return;278 }279 if (!fcn) {280 res.status(400).json(getErrorMessage('\'fcn\''));281 return;282 }283 if (!args) {284 res.status(400).json(getErrorMessage('\'args\''));285 return;286 }287 args = args.replace(/'/g, '"');288 args = JSON.parse(args);289 logger.debug(args);290 let message = await query.queryChaincode(peer, channelName, chaincodeName, args, fcn, req.username, req.orgname);291 res.status(200).send(message);292});293// Query Get Block by BlockNumber294app.get('/channels/:channelName/blocks/:blockId', async function (req, res) {295 logger.debug('==================== GET BLOCK BY NUMBER ==================');296 let blockId = req.params.blockId;297 let peer = req.query.peer;298 logger.debug('channelName : ' + req.params.channelName);299 logger.debug('BlockID : ' + blockId);300 logger.debug('Peer : ' + peer);301 if (!blockId) {302 res.status(400).json(getErrorMessage('\'blockId\''));303 return;304 }305 let message = await query.getBlockByNumber(peer, req.params.channelName, blockId, req.username, req.orgname);306 res.status(200).send(message);307});308// Query Get Transaction by Transaction ID309app.get('/channels/:channelName/transactions/:trxnId', async function (req, res) {310 logger.debug('================ GET TRANSACTION BY TRANSACTION_ID ======================');311 logger.debug('channelName : ' + req.params.channelName);312 let trxnId = req.params.trxnId;313 let peer = req.query.peer;314 if (!trxnId) {315 res.status(400).json(getErrorMessage('\'trxnId\''));316 return;317 }318 let message = await query.getTransactionByID(peer, req.params.channelName, trxnId, req.username, req.orgname);319 res.status(200).send(message);320});321// Query Get Block by Hash322app.get('/channels/:channelName/blocks', async function (req, res) {323 logger.debug('================ GET BLOCK BY HASH ======================');324 logger.debug('channelName : ' + req.params.channelName);325 let hash = req.query.hash;326 let peer = req.query.peer;327 if (!hash) {328 res.status(400).json(getErrorMessage('\'hash\''));329 return;330 }331 let message = await query.getBlockByHash(peer, req.params.channelName, hash, req.username, req.orgname);332 res.status(200).send(message);333});334//Query for Channel Information335app.get('/channels/:channelName', async function (req, res) {336 logger.debug('================ GET CHANNEL INFORMATION ======================');337 logger.debug('channelName : ' + req.params.channelName);338 let peer = req.query.peer;339 let message = await query.getChainInfo(peer, req.params.channelName, req.username, req.orgname);340 res.status(200).send(message);341});342//Query for Channel instantiated chaincodes343app.get('/channels/:channelName/chaincodes', async function (req, res) {344 logger.debug('================ GET INSTANTIATED CHAINCODES ======================');345 logger.debug('channelName : ' + req.params.channelName);346 let peer = req.query.peer;347 let message = await query.getInstalledChaincodes(peer, req.params.channelName, 'instantiated', req.username, req.orgname);348 res.status(200).send(message);349});350// Query to fetch all Installed/instantiated chaincodes351app.get('/chaincodes', async function (req, res) {352 var peer = req.query.peer;353 var installType = req.query.type;354 logger.debug('================ GET INSTALLED CHAINCODES ======================');355 let message;356 if (installType === 'installed') {357 logger.debug('<< Installed Chaincodes >>');358 message = await query.getInstalledChaincodes(peer, null, 'installed', req.username, req.orgname)359 } else {360 logger.debug('<< Instantiated Chaincodes >>');361 message = await query.getInstalledChaincodes(peer, null, 'instantiated', req.username, req.orgname)362 }363 res.status(200).send(message);364});365// Query to fetch channels366app.get('/channels', async function (req, res) {367 logger.debug('================ GET CHANNELS ======================');368 logger.debug('peer: ' + req.query.peer);369 logger.debug('username: ' + req.username);370 logger.debug('orgname: ' + req.orgname);371 var peer = req.query.peer;372 if (!peer) {373 res.status(400).json(getErrorMessage('\'peer\''));374 return;375 }376 let message = await query.getChannels(peer, req.username, req.orgname);377 res.status(200).send(message);378});379//Query to get all Orgs in a channel380app.get('/orgs/:channelName/chaincode', async function (req, res) {381 logger.debug('================ GET ORGS IN A CHANNEL ======================');382 logger.debug('username: ' + req.username);383 logger.debug('orgname: ' + req.orgname);384 logger.debug('channelName: ' + req.params.channelName);385 // logger.debug('peer: ' + req.query.peer);386 var channelName = req.params.channelName;387 if (!channelName) {388 res.status(400).json(getErrorMessage('\'channelName\''));389 return;390 }391 /* var peer = req.query.peer;392 if (!peer) {393 res.status(400).json(getErrorMessage('\'peer\''));394 return;395 }*/396 let message = await query.getOrgs(channelName, req.username, req.orgname);397 res.status(200).send(message);398});399//Query to get no of blocks in the channel400app.get('/transactions/:channelName', async function (req, res) {401 logger.debug('================ GET Maximum transactions in the latest block ======================');402 logger.debug('username: ' + req.username);403 logger.debug('orgname: ' + req.orgname);404 logger.debug('channelName: ' + req.params.channelName);405 var channelName = req.params.channelName;406 if (!channelName) {407 res.status(400).json(getErrorMessage('\'channelName\''));408 return;409 }410 var peer = req.query.peer;411 if (!peer) {412 res.status(400).json(getErrorMessage('\'peer\''));413 return;414 }415 let message = await query.getLatestBlock(peer, channelName, req.username, req.orgname);416 res.status(200).send(message);417});418//Query to Peers in a channel419app.get('/Peers/:channelName', async function (req, res) {420 logger.debug('================ GET Peers ======================');421 logger.debug('username: ' + req.username);422 logger.debug('orgname: ' + req.orgname);423 logger.debug('channelName: ' + req.params.channelName);424 var channelName = req.params.channelName;425 if (!channelName) {426 res.status(400).json(getErrorMessage('\'channelName\''));427 return;428 }429 /* var peer = req.query.peer;430 if (!peer) {431 res.status(400).json(getErrorMessage('\'peer\''));432 return;433 }*/434 let message = await query.getPeers(channelName, req.username, req.orgname);435 res.status(200).send(message);436});437//Query to get maximum transaction count in the latest block438app.get('/Totaltransactions/:channelName', async function (req, res) {439 logger.debug('================ GET Maximum transactions in the latest block ======================');440 logger.debug('username: ' + req.username);441 logger.debug('orgname: ' + req.orgname);442 logger.debug('channelName: ' + req.params.channelName);443 var channelName = req.params.channelName;444 if (!channelName) {445 res.status(400).json(getErrorMessage('\'channelName\''));446 return;447 }448 var peer = req.query.peer;449 if (!peer) {450 res.status(400).json(getErrorMessage('\'peer\''));451 return;452 }453 let message = await query.getTotalTransactions(peer, channelName, req.username, req.orgname);454 res.status(200).send(message);455});456//Query to get all block info457app.get('/AllBlocks/:channelName', async function (req, res) {458 logger.debug('================ GET Maximum transactions in the latest block ======================');459 logger.debug('username: ' + req.username);460 logger.debug('orgname: ' + req.orgname);461 logger.debug('channelName: ' + req.params.channelName);462 var channelName = req.params.channelName;463 if (!channelName) {464 res.status(400).json(getErrorMessage('\'channelName\''));465 return;466 }467 var peer = req.query.peer;468 if (!peer) {469 res.status(400).json(getErrorMessage('\'peer\''));470 return;471 }472 let message = await query.getAllBlocks(peer, channelName, req.username, req.orgname);473 res.status(200).send(message);474});475//Query to get all transactions info476app.get('/AllTransactions/:channelName', async function (req, res) {477 logger.debug('================ GET Maximum transactions in the latest block ======================');478 logger.debug('username: ' + req.username);479 logger.debug('orgname: ' + req.orgname);480 logger.debug('channelName: ' + req.params.channelName);481 var channelName = req.params.channelName;482 if (!channelName) {483 res.status(400).json(getErrorMessage('\'channelName\''));484 return;485 }486 var peer = req.query.peer;487 if (!peer) {488 res.status(400).json(getErrorMessage('\'peer\''));489 return;490 }491 let message = await query.getAllTransactions(peer, channelName, req.username, req.orgname);492 res.status(200).send(message);493});494//Query to Peers in a channel495app.get('/ChannelPeer/:channelName', async function (req, res) {496 logger.debug('================ GET Peers ======================');497 logger.debug('username: ' + req.username);498 logger.debug('orgname: ' + req.orgname);499 logger.debug('channelName: ' + req.params.channelName);500 var channelName = req.params.channelName;501 if (!channelName) {502 res.status(400).json(getErrorMessage('\'channelName\''));503 return;504 }505 var peer = req.query.peer;506 if (!peer) {507 res.status(400).json(getErrorMessage('\'peer\''));508 return;509 }510 let message = await query.getPeer(peer, channelName, req.username, req.orgname);511 res.status(200).send(message);512});513// Create Channel with script514app.post('/channel-create-script', async function (req, res) {515 logger.info('<<<<<<<<<<<<<<<<< C R E A T E C H A N N E L w i t h s c r i p t>>>>>>>>>>>>>>>>>');516 logger.debug('End point : /channel-create-script');517 var orgName = req.body.orgName;518 var domainName = req.body.domainName;519 var channelName = req.body.channelName;520 logger.debug('orgName : ' + orgName);521 logger.debug('domainName : ' + domainName);522 logger.debug('channelName : ' + channelName);523 if (!orgName) {524 res.status(400).json(getErrorMessage('\'orgName\''));525 return;526 }527 if (!domainName) {528 res.status(400).json(getErrorMessage('\'domainName\''));529 return;530 }531 if (!channelName) {532 res.status(400).json(getErrorMessage('\'channelName\''));533 return;534 }535 // let message = await createChannel.createChannel(channelName, channelConfigPath, req.username, req.orgname);536 // shell.exec('../../myscript.sh');537 //shell.exec('cd $HOME/dlt-network-base; pwd; ./createChannelFabric.sh ' + orgName + ' ' + domainName + ' ' + channelName);538 //res.status(200).send('success');539 shell.exec('cd ../.. ; ./createChannelFabric.sh ' + orgName + ' ' + domainName + ' ' + channelName, function (code, stdout, stderr) {540 console.log('Exit code:', code);541 console.log('Program output:', stdout);542 console.log('Program stderr:', stderr);543 if (code != 0) {544 res.status(400).send({ "stdout": stdout, "stderr": stderr, "code": code });545 } else {546 res.status(200).send({ "stdout": stdout, "stderr": stderr, "code": code });547 }548 });549});550// Join Channel with script551app.post('/channel-join-script', async function (req, res) {552 logger.info('<<<<<<<<<<<<<<<<< J O I N C H A N N E L W I T H S C R I P T >>>>>>>>>>>>>>>>>');553 logger.debug('End point : /channel-join-script');554 var orgName = req.body.orgName;555 var orgUserId = req.body.orgUserId;556 var orgServerIp = req.body.orgServerIp;557 var channelName = req.body.channelName;558 var domainName = req.body.domainName;559 var baseOrgName = req.body.baseOrgName;560 var signingOrgs = req.body.signingOrgs;561 var orgArray = '';562 for (let i = 0; i < signingOrgs.length; i++) {563 orgArray = orgArray + signingOrgs[i].orgName + ' ' + signingOrgs[i].userId + ' ' + signingOrgs[i].serverIp + ' ';564 }565 logger.debug('orgName : ' + orgName);566 logger.debug('orgUserId : ' + orgUserId);567 logger.debug('orgServerIp : ' + orgServerIp);568 logger.debug('channelName : ' + channelName);569 logger.debug('domainName : ' + domainName);570 logger.debug('baseOrgName : ' + baseOrgName);571 logger.debug('orgArray : ' + orgArray);572 if (!orgName) {573 res.status(400).json(getErrorMessage('\'orgName\''));574 return;575 }576 if (!orgUserId) {577 res.status(400).json(getErrorMessage('\'orgUserId\''));578 return;579 }580 if (!orgServerIp) {581 res.status(400).json(getErrorMessage('\'orgServerIp\''));582 return;583 }584 if (!domainName) {585 res.status(400).json(getErrorMessage('\'domainName\''));586 return;587 }588 if (!channelName) {589 res.status(400).json(getErrorMessage('\'channelName\''));590 return;591 }592 if (!baseOrgName) {593 res.status(400).json(getErrorMessage('\'baseOrgName\''));594 return;595 }596 shell.exec('cd ../.. ; ./channeljoin_ss_fabric.sh ' + orgName + ' ' + orgUserId + ' ' + orgServerIp + ' ' + channelName + ' ' + domainName + ' ' + baseOrgName + ' ' + orgArray, function (code, stdout, stderr) {597 console.log('Exit code:', code);598 console.log('Program output:', stdout);599 console.log('Program stderr:', stderr);600 if (code != 0) {601 res.status(400).send({ "stdout": stdout, "stderr": stderr, "code": code });602 } else {603 res.status(200).send({ "stdout": stdout, "stderr": stderr, "code": code });604 }605 });606});607// sshAuthenticationKeyUpdate608app.post('/sshAuthenticationKeyUpdate', async function (req, res) {609 logger.info('<<<<<<<<<<<<<<<<< SSH AUTHENTICATION KEY UPDATE t>>>>>>>>>>>>>>>>>');610 logger.debug('End point : /sshAuthenticationKeyUpdate');611 var sshPublicKey = req.body.sshPublicKey;612 logger.debug('sshPublicKey : ' + sshPublicKey);613 if (!sshPublicKey) {614 res.status(400).json(getErrorMessage('\'sshPublicKey\''));615 return;616 }617 try {618 var key = fs.readFileSync("./../../../.ssh/authorized_keys", "utf8");619 if (key.includes(sshPublicKey)) {620 console.log('key already existing')621 res.status(200).send('key already existing');622 } else {623 console.log('key not available.adding the key: ==> ' + sshPublicKey)624 fs.appendFile('./../../../.ssh/authorized_keys', sshPublicKey + "\n", 'utf8',625 // callback function626 function (err) {627 if (err) throw err;628 // if no error629 console.log("Data is appended to file successfully.")630 res.status(200).send("PublicKey has appended to file successfully");631 });632 }633 } catch (err) {634 console.log(err.stack || String(err));635 }636});637/*app.get('/networkHealth', async function (req, res) {638 logger.info('<<<<<<<<<<<<<<<<< G E T N E T W O R K H E A L T H W I T H S C R I P T >>>>>>>>>>>>>>>>>');639 logger.debug('End point : /networkHealth');640 shell.exec('cd ../.. ; ./network_health.sh', function (code, stdout, stderr) {641 console.log('Exit code:', code);642 console.log('Program output:', stdout);643 console.log('Program stderr:', stderr);644 res.status(200).send(stdout);645 });646});*/647// Get block file of Channel 648app.post('/getChannelBlockFile', async function (req, res) {649 logger.info('<<<<<<<<<<<<<<<<< G E T C H A N N E L B L O C K >>>>>>>>>>>>>>>>>');650 logger.debug('End point : /getChannelBlockFile');651 var channelName = req.body.channelName;652 logger.info(channelName);653 var blockFilePath = "./../channels/" + channelName + "/" + channelName + ".block";654 console.log(blockFilePath);655 // var key = fs.readFileSync(blockFilePath, "utf8");656 let buff = fs.readFileSync(blockFilePath);657 let base64data = buff.toString('base64');658 // let buff = new Buffer(key);659 // let base64data = buff.toString('base64');660 logger.debug(base64data);661 res.status(200).send({ "stdout": '', "stderr": '', "code": '', "data": base64data });662});663// Create File from Block data664app.post('/createFileFromBlock', async function (req, res) {665 logger.info('<<<<<<<<<<<<<<<<< G E T C H A N N E L B L O C K >>>>>>>>>>>>>>>>>');666 logger.debug('End point : /getChannelBlockFile');667 var channelName = req.body.channelName;668 var data = req.body.data;669 logger.info(channelName);670 var fileName = channelName + ".block";671 //fs.writeFile(fileName, data, (err) => {672 // if (err) throw err;673 // console.log('The file has been saved!');674 // });675 let buff = new Buffer(data, 'base64');676 fs.writeFileSync(fileName, buff);677 res.status(200).send({ "stdout": '', "stderr": '', "code": '', "data": "file created" });678});679// Copy msp folder680app.post('/copyMspFolder', async function (req, res) {681 logger.info('<<<<<<<<<<<<<<<< COPY MSP FOLDER >>>>>>>>>>>>>>>>>');682 logger.debug('End point : /copyMspFolder');683 var orgName = req.body.orgName;684 logger.info(orgName);685 var tlsPath = "./../crypto-config/peerOrganizations/" + orgName + ".dlt-domain.com/msp/tlscacerts/tlsca." + orgName + ".dlt-domain.com-cert.pem";686 var caPath = "./../crypto-config/peerOrganizations/" + orgName + ".dlt-domain.com/msp/cacerts/ca." + orgName + ".dlt-domain.com-cert.pem";687 var adminPath = "./../crypto-config/peerOrganizations/" + orgName + ".dlt-domain.com/msp/admincerts/Admin@" + orgName + ".dlt-domain.com-cert.pem";688 var ordererCaPath = "./..//crypto-config/ordererOrganizations/dlt-domain.com/msp/tlscacerts/tlsca.dlt-domain.com-cert.pem";689 logger.info("tlscert path : " + tlsPath);690 logger.info("cacert path : " + caPath);691 logger.info("admincert path : " + adminPath);692 logger.info("ordererCacert path : " + ordererCaPath);693 try {694 var tlscert = fs.readFileSync(tlsPath);695 var base64tlscert = tlscert.toString('base64');696 var cacert = fs.readFileSync(caPath);697 var base64cacert = cacert.toString('base64');698 var admincert = fs.readFileSync(adminPath);699 var base64admincert = admincert.toString('base64');700 var ordererCacert = fs.readFileSync(ordererCaPath);701 var base64ordererCacert = ordererCacert.toString('base64');702 res.status(200).send({ "tlscert": base64tlscert, "cacert": base64cacert, "admincert": base64admincert, "base64ordererCacert": base64ordererCacert });703 } catch (e) {704 logger.info(e);705 res.status(400).send(e);706 }707});708var createFilesAndFolder = function (cert, path, certPath) {709 return new Promise((resolve, reject) => {710 mkdirp(path, function (err) {711 if (err) {712 logger.error("Error creating directory" + path, err);713 reject(err);714 // return res.status(400).send(err);715 } else {716 logger.info('sucessfully created #' + path + '#');717 let tlsbuff = new Buffer(cert, 'base64');718 fs.writeFile(certPath, tlsbuff, (err) => {719 if (err) {720 logger.error("Error creating file" + certPath, err);721 reject(err);722 } else {723 logger.info("Successfully created the msp file: " + certPath);724 resolve(certPath + 'created successfully.');725 }726 });727 }728 });729 });730 731}732// staticChannelCreation script733app.post('/fabricChannelCreate', async function (req, res) {734 logger.info('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');735 logger.info('<<<<<<<<<<<<<<<<< Static channel creation script >>>>>>>>>>>>>>>>>');736 logger.info('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');737 logger.debug('End point : /fabricChannelCreate');738 try {739 var baseOrgName = req.body.baseOrgName;740 var domainName = req.body.domainName;741 var channelName = req.body.channelName;742 var orgArray = req.body.orgArray;743 var scriptOrgArray = '';744 logger.debug('baseOrgName : ' + baseOrgName);745 logger.debug('domainName : ' + domainName);746 logger.debug('channelName : ' + channelName);747 logger.debug('orgArray : ' + orgArray);748 749 let promises = [];750 for (let i = 0; i < orgArray.length; i++) {751 scriptOrgArray = scriptOrgArray + orgArray[i].newOrg + ' ';752 var newOrg = orgArray[i].newOrg;753 var tlscert = orgArray[i].tlscert;754 var cacert = orgArray[i].cacert;755 var admincert = orgArray[i].admincert;756 logger.info(newOrg);757 logger.info(tlscert);758 logger.info(cacert);759 logger.info(admincert);760 var tlsPath = "./../partnerOrgs/" + newOrg + "-config/msp/tlscacerts";761 var caPath = "./../partnerOrgs/" + newOrg + "-config/msp/cacerts";762 var adminPath = "./../partnerOrgs/" + newOrg + "-config/msp/admincerts";763 var tlsCertPath = "./../partnerOrgs/" + newOrg + "-config/msp/tlscacerts/tlsca." + newOrg + ".dlt-domain.com-cert.pem";764 var caCertPath = "./../partnerOrgs/" + newOrg + "-config/msp/cacerts/ca." + newOrg + ".dlt-domain.com-cert.pem";765 var adminCertPath = "./../partnerOrgs/" + newOrg + "-config/msp/admincerts/Admin@" + newOrg + ".dlt-domain.com-cert.pem";766 promises.push(createFilesAndFolder(tlscert, tlsPath, tlsCertPath));767 promises.push(createFilesAndFolder(cacert, caPath, caCertPath));768 promises.push(createFilesAndFolder(admincert, adminPath, adminCertPath));769 }770 Promise.all(promises).then(function(data) {771 logger.info("All promises returned..");772 shell.exec('cd ../.. ; ./fabric_channel_create.sh ' + baseOrgName + ' ' + domainName + ' ' + channelName + ' ' + scriptOrgArray, function (code, stdout, stderr) {773 logger.info('Exit code:', code);774 logger.info('Program output:', stdout);775 logger.info('Program stderr:', stderr);776 if (code != 0) {777 return res.status(400).send({ "success": false,"stdout": stdout, "stderr": stderr, "code": code });778 }779 780 var blockFilePath = "./../channels/" + channelName + "/" + channelName + ".block";781 logger.info("BlockFilePath: " + blockFilePath);782 let buff = fs.readFileSync(blockFilePath);783 let base64data = buff.toString('base64');784 logger.debug(base64data);785 return res.status(200).send({ "success": true, "message": "api exicuted sucessfully", "block": base64data });786 });787 }, function(err) {788 logger.error('Error creating certificate FileList. Cannot proceed with blockfile creation.')789 return res.status(400).send(err);790 });791 792 } catch (e) {793 logger.info(e);794 return res.status(400).send({ "success": false,"stdout": stdout, "stderr": stderr, "code": code });795 }796 797});798// newPeerJoinScript.sh799app.post('/fabricChannelJoin', async function (req, res) {800 logger.info('<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>');801 logger.info('<<<<<<<<<<<<<<<<< NEW PEER JOIN SCRIPT >>>>>>>>>>>>>>>>>');802 logger.info('<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>');803 logger.debug('End point : /fabricChannelJoin');804 var orgName = req.body.orgName;805 var domainName = req.body.domainName;806 var channelName = req.body.channelName;807 var baseOrg = req.body.baseOrg;808 var baseServerIp = req.body.baseServerIp;809 var baseOrdererCaCert = req.body.baseOrdererCaCert;810 var block = req.body.block;811 logger.info(orgName);812 logger.info(domainName);813 logger.info(channelName);814 logger.info(baseOrg);815 logger.info(baseServerIp);816 logger.info(baseOrdererCaCert);817 try {818 var caPath0 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer0." + baseOrg + ".dlt-domain.com/tls/";819 var caPath1 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer1." + baseOrg + ".dlt-domain.com/tls/";820 var caPath2 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer2." + baseOrg + ".dlt-domain.com/tls/";821 var caCertPath0 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer0." + baseOrg + ".dlt-domain.com/tls/ca.crt";822 var caCertPath1 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer1." + baseOrg + ".dlt-domain.com/tls/ca.crt";823 var caCertPath2 = "./artifacts/channel/crypto-config/ordererOrganizations/dlt-domain.com/orderers/orderer2." + baseOrg + ".dlt-domain.com/tls/ca.crt";824 var channelPath = "./../channels/" + channelName + "/";825 var blockPath = "./../channels/" + channelName + "/" + channelName + ".block";826 mkdirp(caPath0, function (err) {827 if (err) {828 console.error(err);829 res.status(400).send(err);830 } else {831 console.log('sucessfully created #' + caPath0 + '#');832 let cabuff0 = new Buffer(baseOrdererCaCert, 'base64');833 fs.writeFile(caCertPath0, cabuff0, (err) => {834 if (err) {835 console.error(err);836 res.status(400).send(err);837 } else {838 console.log(caCertPath0 + 'created');839 }840 });841 }842 });843 mkdirp(caPath1, function (err) {844 if (err) {845 console.error(err);846 res.status(400).send(err);847 } else {848 console.log('sucessfully created #' + caPath1 + '#');849 let cabuff1 = new Buffer(baseOrdererCaCert, 'base64');850 fs.writeFile(caCertPath1, cabuff1, (err) => {851 if (err) {852 console.error(err);853 res.status(400).send(err);854 } else {855 console.log(caCertPath1 + 'created');856 }857 });858 }859 });860 mkdirp(caPath2, function (err) {861 if (err) {862 console.error(err);863 res.status(400).send(err);864 } else {865 console.log('sucessfully created #' + caPath2 + '#');866 let cabuff2 = new Buffer(baseOrdererCaCert, 'base64');867 fs.writeFile(caCertPath2, cabuff2, (err) => {868 if (err) {869 console.error(err);870 res.status(400).send(err);871 } else {872 console.log(caCertPath2 + 'created');873 }874 });875 }876 });877 mkdirp(channelPath, function (err) {878 if (err) {879 console.error(err);880 res.status(400).send(err);881 } else {882 console.log('sucessfully created #' + channelPath + '#');883 let channelbuff = new Buffer(block, 'base64');884 fs.writeFile(blockPath, channelbuff, (err) => {885 if (err) {886 console.error(err);887 res.status(400).send(err);888 } else {889 console.log(blockPath + 'created');890 }891 });892 }893 });894 shell.exec('cd ../.. ; ./fabric_channel_join.sh ' + orgName + ' ' + domainName + ' ' + channelName + ' ' + baseOrg + ' ' + baseServerIp, function (code, stdout, stderr) {895 console.log('Exit code:', code);896 console.log('Program output:', stdout);897 console.log('Program stderr:', stderr);898 if (code != 0) {899 res.status(400).send({ "success": false,"stdout": stdout, "stderr": stderr, "code": code });900 } else {901 res.status(200).send({ "success": true,"stdout": stdout, "stderr": stderr, "code": code });902 }903 });904 } catch (e) {905 logger.info(e);906 res.status(400).send(e);907 }...

Full Screen

Full Screen

service.js

Source:service.js Github

copy

Full Screen

1const { v1: uuidv1 } = require('uuid');2const constants = require('./constants');3var channels = {};4var users = {}5module.exports = {6 handlePrivateMessage: (req, res) => {7 var data = req.body;8 var channelName = data["channelName"];9 var senderId = data["senderId"];10 var receiverId = data["receiverId"];11 var message = data["message"];12 var isAnonymous = data["isAnonymous"];13 var response = {}14 if(channels[channelName] && users[senderId] && users[receiverId] && message){15 var result = {};16 result["message_type"] = "Chat_Message";17 result["status"] = constants.SUCCESS;18 result["message"] = message;19 result["isPrivate"] = true;20 if(!isAnonymous){21 result["sender_name"] = users[senderId]["userName"];22 result["senderId"] = senderId;23 }else{24 result["sender_name"] = "Anonymous";25 }26 users[senderId]["ws"].send(JSON.stringify(result));27 users[receiverId]["ws"].send(JSON.stringify(result));28 res.status(201);29 response["data"] = { "message":"SUCCESS"};30 }else{31 res.status(400);32 response["data"] = { "message":"BAD REQUEST"};33 }34 res.json(response);35 },36 broadCastMemberInfo: (channelName, result) => {37 if(channelName in channels){38 var usersList = channels[channelName]["users"];39 console.log("broadcasting message....");40 for(var index = 0; index < usersList.length; index++){41 try{42 usersList[index]["ws"].send(JSON.stringify(result));43 }44 catch(err){45 console.log("error while sending message for user ",usersList[index]);46 console.log(err);47 }48 }49 }50 },51 terminateChannel: (channelName) => {52 if(channelName in channels && channels[channelName]["users"].length == 0){53 delete channels[channelName];54 }55 },56 handleTerminateUser : (channelName, userId) => {57 console.log(channelName+ " " +userId);58 if(channelName in channels){59 if(userId in users){60 var indexToDelete = -1;61 var usersList = channels[channelName]["users"];62 for(var index = 0; index < usersList.length; index++){63 if(usersList[index]["userId"] == userId){64 indexToDelete = index;65 break;66 }67 }68 channels[channelName]["users"].splice(indexToDelete,1);69 delete users[userId];70 var response = {};71 response["message_type"] = "Member_Info";72 response["status"] = 200;73 response["action"] = "remove";74 response["userId"] = userId;75 module.exports.broadCastMemberInfo(channelName,response);76 module.exports.terminateChannel(channelName);77 }78 }79 },80 terminateUserFromChannel : (req, res) => {81 var data = req.body;82 var channelName = data["channelName"];83 var userId = data["userId"];84 module.exports.handleTerminateUser(channelName, userId);85 res.status(200);86 res.json({"message":"success"});87 },88 joinChannel : (req,res)=>{89 var data = req.body;90 var channelName = data["channelName"];91 var userName = data["userName"];92 var response = {};93 if(channelName in channels){94 user = {};95 user["userName"] = userName;96 user["userId"] = uuidv1();97 user["channel"] = channelName;98 users[user["userId"]] = user;99 response["channelName"] = channelName;100 response["userId"] = user["userId"];101 response["message"] = "user added to channel!!";102 res.status(201);103 }else{104 res.status(400);105 response["message"] = "Sorry Channel does not exists!!";106 }107 var result = {};108 result["data"] = response;109 res.json(result);110 },111 getMembersByChannelName: function(req, res){112 var channelName = req.query.channel;113 console.log(channelName,channels);114 var response = {};115 if(channelName in channels){116 var members = channels[channelName]["users"];117 response["data"] = members;118 res.status(200);119 }else{120 res.status(400);121 response["message"] = "Channel Doesn't Exists";122 }123 res.json(response);124 },125 isChannelExists : function(req,res){126 var channelName = req.query.channel;127 var softCreate = req.query.softCreate == 'true';128 var response = {}129 if(channelName in channels){130 res.status(200);131 response["message"] = "Channel Exists";132 }else{133 if(softCreate){134 channels[channelName] = {135 "name" : channelName,136 "users" : []137 };138 res.status(200);139 response["message"] = "Channel Exists";140 }else{141 res.status(400);142 response["message"] = "Channel Does not Exists";143 }144 }145 var result = {};146 result["data"] = response;147 res.json(result);148 },149 createChannel : (req,res)=>{150 var data = req.body;151 var channelName = data["channelName"];152 var userName = data["userName"];153 var response = {};154 if(channelName in channels){155 response["message"] = "Channel already exists !!";156 res.status(400);157 }else{158 channels[channelName] = {159 "name" : channelName,160 "users" : []161 };162 user = {};163 user["userName"] = userName;164 user["userId"] = uuidv1();165 user["channel"] = channelName;166 users[user["userId"]] = user;167 response["channelName"] = channelName;168 response["userId"] = user["userId"];169 response["message"] = "Channel created!!";170 res.status(201);171 }172 var result = {};173 result["data"] = response;174 res.json(result);175 },176 updateUserInChannel: function(userId,channelName,ws){177 var usersList = channels[channelName]["users"];178 for(var index = 0; index < usersList.length; index++){179 if(usersList[index]["userId"] == userId){180 usersList[index]["ws"] = ws;181 return true;182 }183 }184 users[userId]["ws"] = ws;185 channels[channelName]["users"].push(users[userId]);186 },187 establishSocketConnection : function(ws,req){188 //console.log(ws);189 var channelName = req.params["channelName"];190 var userId = req.params["userId"];191 var response = {};192 response["message_type"] = "Connection_Status";193 if(channelName in channels){194 if(userId in users){195 module.exports.updateUserInChannel(userId,channelName,ws);196 response["status"] = constants.SUCCESS;197 response["message"] = "Connection establised with Channel";198 }else{199 response["status"] = constants.INVALID_DATA;200 response["message"] = "Invalid User";201 }202 }else{203 response["status"] = constants.INVALID_DATA;204 response["message"] = "Invalid Channel Name";205 }206 ws.on('message',handleSocketResponse);207 ws.on('open',connectionOpen);208 ws.on('close',connectionClose);209 ws.send(JSON.stringify(response));210 setTimeout(function(){211 var userObj = {...users[userId]};212 userObj["ws"] = null;213 var response = {};214 response["message_type"] = "Member_Info";215 response["status"] = 200;216 response["action"] = "add";217 response["user"] = userObj;218 module.exports.broadCastMemberInfo(channelName,response);219 },5000);220 function connectionOpen(){221 console.log("connection opened");222 }223 function connectionClose(){224 console.log("connection closed");225 console.log(channelName+ " " +userId);226 module.exports.handleTerminateUser(channelName, userId);227 }228 function validateInput(channelName, senderId, message)229 {230 var error = 0;231 if(message == "") { error++; }232 if((channelName in channels) == false) { error++; }233 if((senderId in users) == false) { error++; }234 return error == 0 ? true : false;235 }236 function handleSocketResponse(msg){237 var body = JSON.parse(msg);238 var channelName = body["channelName"];239 var senderId = body["senderId"];240 var message = body["message"];241 var isAnonymous = body["isAnonymous"]242 var result = {};243 result["message_type"] = "Chat_Message";244 if(!validateInput(channelName,senderId,message)){245 result["status"] = constants.INVALID_DATA;246 result["message"] = "Invalid Credentials";247 user[senderId]["ws"].send(JSON.stringify(result));248 return;249 }250 result["status"] = constants.SUCCESS;251 result["message"] = message;252 result["isPrivate"] = false;253 if(!isAnonymous){254 result["sender_name"] = users[senderId]["userName"];255 result["senderId"] = senderId;256 }else{257 result["sender_name"] = "Anonymous";258 }259 var usersList = channels[channelName]["users"];260 for(var index = 0; index < usersList.length; index++){261 usersList[index]["ws"].send(JSON.stringify(result));262 }263 }264 }...

Full Screen

Full Screen

ChatResolver.ts

Source:ChatResolver.ts Github

copy

Full Screen

1import {2 Arg,3 Ctx,4 Mutation,5 Query,6 Resolver,7 Subscription,8 UseMiddleware,9 PubSub,10 PubSubEngine,11 Root,12} from "type-graphql";13import { Chat, User } from "./entity/Entities";14import { Channel, UsersInChannel } from "./entity/Other";15let chats: Chat[] = [];16const allChannels: string[] = [];17@Resolver()18export class ChatResolver {19 @Mutation(() => Boolean)20 async createChannel(@Arg("channelName") channelName: string) {21 const channelFound = await Channel.findOne({ where: { channelName } });22 if (!channelFound) {23 Channel.insert({24 channelName,25 });26 allChannels.push(channelName);27 return true;28 }29 return false;30 }31 @Query(() => [Channel])32 getChannels() {33 return Channel.find();34 }35 @Query(() => Channel, { nullable: true })36 async getChannelByName(@Arg("channelName") channelName: string) {37 const channelFound = await Channel.findOne({ where: { channelName } });38 if (channelFound) {39 return channelFound;40 }41 return null;42 }43 @Query(() => [Chat])44 async getChats(@Arg("channelName") channelName: string) {45 const channelChats = await Chat.find({ where: { channelName } });46 return channelChats;47 }48 @Mutation(() => Boolean)49 async deleteChatsFromChannel(@Arg("channelName") channelName: string) {50 const channelFound = await Channel.findOne({ where: { channelName } });51 if (channelFound) {52 const channelChats = await Chat.find({ where: { channelName } });53 try {54 Chat.remove(channelChats);55 } catch (err) {56 console.log(err);57 return false;58 }59 return true;60 } else {61 return false;62 }63 }64 @Mutation(() => Boolean)65 async deleteChannel(@Arg("channelName") channelName: string) {66 const channelFound = await Channel.findOne({ where: { channelName } });67 if (channelFound) {68 try {69 Channel.remove(channelFound);70 const channelChats = await Chat.find({71 where: { channelName },72 });73 try {74 Chat.remove(channelChats);75 } catch (err) {76 console.log(err);77 return false;78 }79 return true;80 } catch (err) {81 console.log(err);82 return false;83 }84 } else {85 return false;86 }87 }88 @Mutation(() => Boolean)89 async deleteAllChannels() {90 const channels = await Channel.find();91 if (channels) {92 try {93 for (let i = 0; i < channels.length; i++) {94 Channel.remove(channels[i]);95 let channelName = channels[i].channelName;96 const channelChats = await Chat.find({97 where: { channelName },98 });99 Chat.remove(channelChats);100 }101 return true;102 } catch (err) {103 console.log(err);104 return false;105 }106 } else {107 return false;108 }109 }110 @Mutation(() => Chat, { nullable: true })111 async createChat(112 @PubSub() pubsub: PubSubEngine,113 @Arg("user") user: string,114 @Arg("message") message: string,115 @Arg("channelName") channelName: string116 ) {117 const channelFound = await Channel.findOne({ where: { channelName } });118 if (channelFound) {119 const chat = { user, message, channelName };120 try {121 await Chat.insert(chat);122 } catch (err) {123 console.log(err);124 return false;125 }126 const payload = chat;127 await pubsub.publish(channelFound.channelName, payload);128 return chat;129 }130 return null;131 }132 @Mutation(() => UsersInChannel, { nullable: true })133 async addToChannelUserList(134 @Arg("username") username: string,135 @Arg("channelName") channelName: string,136 @Arg("channelRole") channelRole: string137 ) {138 const user = await User.findOne({ where: { username } });139 const channel = await Channel.findOne({ where: { channelName } });140 if (user && channel) {141 if (142 channel.users.find((x) => JSON.parse(x).name === user.username)143 ) {144 return null;145 }146 channel.users.push(147 JSON.stringify({ name: user.username, role: channelRole })148 );149 await Channel.update(channel.id, channel);150 return { channelName, users: channel.users };151 }152 return null;153 }154 @Query(() => UsersInChannel, { nullable: true })155 async getChannelUsers(156 @PubSub() pubsub: PubSubEngine,157 @Arg("channelName") channelName: string158 ) {159 const channel = await Channel.findOne({ where: { channelName } });160 if (!channel) {161 return null;162 }163 let userTopic = channelName + "-users";164 await pubsub.publish(userTopic, {165 channelName,166 users: channel.users,167 });168 return { channelName: channelName, users: channel.users };169 }170 @Subscription({ topics: ({ args }) => args.channel })171 messageSent(172 @Arg("channel") _channel: string,173 @Root() { id, user, message, channelName }: Chat174 ): Chat {175 return { id, user, message, channelName } as any;176 }177 @Subscription(() => UsersInChannel, { topics: ({ args }) => args.channel })178 usersInChannel(179 @Arg("channel") _channel: string,180 @Root() channelUsers: UsersInChannel181 ): UsersInChannel {182 return channelUsers;183 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.channelName(function(err, data) {4 console.log(data);5});6Your name to display (optional):7Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');3wpt.channelName('mychannel', function(err, data) {4 console.log(data);5});6var wpt = require('wpt-api');7var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');8wpt.channelList(function(err, data) {9 console.log(data);10});11var wpt = require('wpt-api');12var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');13wpt.channelDelete('mychannel', function(err, data) {14 console.log(data);15});16var wpt = require('wpt-api');17var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');18wpt.channelTest('mychannel', function(err, data) {19 console.log(data);20});21var wpt = require('wpt-api');22var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');23wpt.channelTest('mychannel', function(err, data) {24 console.log(data);25});26var wpt = require('wpt-api');27var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');28wpt.channelTest('mychannel', function(err, data) {29 console.log(data);30});31var wpt = require('wpt-api');32var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');33wpt.channelTest('mychannel

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2console.log('Channel Name: ' + channelName);3var wpt = require('webpagetest');4console.log('Channel Name: ' + channelName);5var wpt = require('webpagetest');6console.log('Channel Name: ' + channelName);7var wpt = require('webpagetest');8console.log('Channel Name: ' + channelName);9var wpt = require('webpagetest');10console.log('Channel Name: ' + channelName);11var wpt = require('webpagetest');12console.log('Channel Name: ' + channelName);13var wpt = require('webpagetest');14console.log('Channel Name: ' + channelName);15var wpt = require('webpagetest');16var channelName = wpt.channelName('http

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