How to use handleSubscription method in Cypress

Best JavaScript code snippet using cypress

streams.js

Source:streams.js Github

copy

Full Screen

1var redis = require('redis');2var nconf = require('nconf');3//require('longjohn')4module.exports = {5 cache: null,6 // we still need to be able to communicate pumps7 dispatcher: null,8 redisClient: null,9 redisListenClient: null,10 reloadTimer: null,11 openPings: {},12 // needs to happen after cache is set13 init: function(redisClientOptions) {14 // FIXME: support15 this.redisClient = redis.createClient(redisClientOptions);16 this.redisListenClient = redis.createClient(redisClientOptions);17 var ref = this;18 ref.redisListenClient.subscribe("AppDotNetWS"); // WS to altapi19 ref.redisListenClient.subscribe("AppDotNetAPI"); // altapi to altpi communication20 ref.redisListenClient.on("message", ref.handleEvent);21 // set up initial listeners (wait for the camintejs connect)22 setTimeout(function() {23 ref.loadSubscriptions();24 }, 1000);25 /*26 setInterval(function() {27 // just incase another thread updates28 // maybe check database count29 // or we can have a scoreboard30 // we just plug into the redis bus31 ref.loadSubscriptions();32 }, 30*1000)33 */34 },35 checkConnections: function() {36 var ref = this;37 this.cache.getAllUserStreams(function(res) {38 // send pings39 var wrap = {40 meta: {41 //connection_id: stream.connection_id,42 type: 'ping'43 },44 data: { id: Date.now() }45 }46 for(var i in res.userStreams) {47 var stream = res.userStreams[i];48 ref.checkConnection(stream, wrap);49 }50 })51 },52 expireConnections: function() {53 var ref = this;54 this.cache.getAllUserStreams(function(res) {55 for(var i in res.userStreams) {56 var stream = res.userStreams[i];57 ref.checkExpire(stream);58 }59 })60 },61 loadSubscriptions: function() {62 //console.log('streams::loadSubscriptions - start');63 // query user_streamsubscriptions for all listeners64 // update our dispatcher data structure that our general pump uses65 // we need to make a key, so it's easy for pump to look up if there's any connections we need to send to66 // we need to do the heavy lifting here..67 var ref = this;68 this.cache.getAllUserStreams(function(res) {69 //console.log('streams::loadSubscriptions - res', res);70 var tokenLookup = {};71 for(var i in res.tokens) {72 var tokenObj = res.tokens[i];73 tokenLookup[tokenObj.id] = tokenObj;74 }75 var subLookup = {};76 for(var i in res.subs) {77 var sub = res.subs[i];78 if (subLookup[sub.user_stream_id] === undefined) {79 subLookup[sub.user_stream_id] = [];80 }81 subLookup[sub.user_stream_id].push(sub);82 }83 ref.dispatcher.pumps = {};84 console.log('streams::loadSubscriptions -', res.userStreams.length, 'streams');85 for(var i in res.userStreams) {86 var stream = res.userStreams[i];87 //console.log('streams::loadSubscriptions -', subLookup[stream.id].length, 'subcriptions for', stream.id, 'streamid');88 // FIXME: remove any existing listeners for this connection89 // FIXME: set up new listeners for this connection90 // send a ping too91 for(var j in subLookup[stream.id]) {92 var sub = subLookup[stream.id][j];93 // threaded doesn't generate multiple events94 // because the creation only happens on one thread95 switch(sub.stream) {96 case '/posts/stream':97 // we can listen to user posts98 // so lets get a list of everyone we're following99 // FIXME: update this list when we follow/unfollow a user100 // subscribe this connection_string_id to all user_posts we need101 ref.cache.getFollowing(stream.userid, {}, function(followings, err) {102 console.log('streams::loadSubscriptions -', stream.userid, 'is following', followings.length, 'users', stream.connection_id);103 for(var k in followings) {104 var following = followings[k];105 var key = 'user.'+following.followsid+'.post';106 if (ref.dispatcher.pumps[key] === undefined) {107 ref.dispatcher.pumps[key] = [];108 }109 ref.dispatcher.pumps[key].push(stream.connection_id);110 }111 });112 break;113 case '/channels':114 // get a list of channels you're subbged to115 ref.cache.getUserSubscriptions(stream.userid, {}, function(subscriptions, err) {116 for(var k in subscriptions) {117 var sub = subscriptions[k];118 var key = 'channel.'+sub.channelid;119 if (ref.dispatcher.pumps[key] === undefined) {120 ref.dispatcher.pumps[key] = [];121 }122 ref.dispatcher.pumps[key].push(stream.connection_id);123 }124 });125 break;126 case '/users/me/posts':127 var key = 'user.'+stream.userid+'.post';128 if (ref.dispatcher.pumps[key] === undefined) {129 ref.dispatcher.pumps[key] = [];130 }131 ref.dispatcher.pumps[key].push(stream.connection_id);132 break;133 default:134 if (sub.stream.match(/^\/channels\/\d+\/messages/)) {135 var match = sub.stream.match(/^\/channels\/(\d+)\/messages/);136 var channelid = match[1];137 //console.log('streams::loadSubscriptions - \/channels\/\d+\/messages channelid', channelid);138 var key = 'channel.'+channelid+'.message';139 if (ref.dispatcher.pumps[key] === undefined) {140 ref.dispatcher.pumps[key] = [];141 }142 ref.dispatcher.pumps[key].push(stream.connection_id);143 } else {144 console.log('streams::loadSubscriptions - implement me', sub.stream);145 }146 break;147 }148 }149 }150 // , ref.dispatcher.pumps151 var keys = []152 for(var key in ref.dispatcher.pumps) {153 keys.push([key, ref.dispatcher.pumps[key].length])154 }155 console.log('streams::loadSubscriptions - final keys', keys.length);156 ref.checkConnections();157 ref.expireConnections();158 });159 },160 loadSubscription: function(stream) {161 },162 checkConnection: function(stream, wrap) {163 var ref=this;164 wrap.meta.connection_id = stream.connection_id;165 if (ref.openPings[stream.connection_id] === undefined) {166 ref.openPings[stream.connection_id] = []167 }168 ref.openPings[stream.connection_id].push(wrap.data.id)169 var idx = ref.openPings[stream.connection_id].indexOf(wrap.data.id)170 ref.handlePublish(stream.connection_id, wrap);171 setTimeout(function() {172 //console.log('checking pings for', stream.connection_id, ref.openPings[stream.connection_id].length);173 var cur = ref.openPings[stream.connection_id].indexOf(wrap.data.id);174 if (cur != -1) {175 //console.log(wrap.data.id, 'ping is still outstanding for', stream.connection_id, 'state', stream.connection_closed_at);176 if (stream.connection_closed_at == null) {177 console.log('streams::checkConnections - marking offline', stream.connection_id);178 module.exports.cache.userStreamUpdate(stream.connection_id, {179 connection_closed_at: new Date()180 }, function(userStream, err) {181 //console.log('userStream updated')182 })183 }184 } else {185 // if has connection_closed_at, we need to clear it186 //console.log('streams::checkConnections - ', stream.connection_id, 'state', stream.connection_closed_at);187 if (stream.connection_closed_at != null) {188 console.log('streams::checkConnections - marking online', stream.connection_id);189 module.exports.cache.userStreamUpdate(stream.connection_id, {190 connection_closed_at: null191 }, function(userStream, err) {192 //console.log('userStream updated')193 })194 }195 }196 }, 30*1000);197 },198 checkExpire: function(stream) {199 // ignore if no auto or online200 if (!stream.auto_delete || stream.connection_closed_at == null) {201 //console.log('stream::checkExpire - skipping, AD:', stream.auto_delete, 'state', stream.connection_closed_at);202 return;203 }204 var now = Date.now();205 var thenD = new Date(stream.connection_closed_at);206 var then = thenD.getTime();207 var diff = now - then;208 //console.log('streams::checkExpire - diff', diff, 'ms')209 if (diff < 10*60*1000) {210 return;211 }212 console.log('streams::checkExpire - disconnected over 10mins ago', stream.connection_id, '@', stream.id);213 this.cache.deleteUserStream(stream.id);214 },215 handlePublish: function(connectionId, data) {216 //console.log('streams::handlePublish - start', connectionId, data);217 //try {218 this.redisClient.publish(connectionId, JSON.stringify(data));219 /*220 } catch(e) {221 console.log('cant publish', e)222 } */223 },224 pendingReloads: 0,225 handleEvent: function(channel, message) {226 // these could be HTTP requests227 //console.log('streams::handleEvent - chan', channel, 'msg', message);228 var ref = module.exports229 if (channel == 'AppDotNetAPI') {230 var pkt = JSON.parse(message)231 //console.log('streams::handleEvent - AppDotNetAPI - message', pkt)232 if (pkt.act == 'sub') {233 // uid,sid,sub {234 // user_stream_id235 // stream236 // params237 // id238 // }239 // time delay this for Xms just incase more come in240 ref.pendingReloads++241 //console.log('streams::handleEvent - AppDotNetAPI - ask for reload')242 // cancel any pending timer, add another Xms243 if (ref.reloadTimer !== null) clearTimeout(ref.reloadTimer)244 ref.reloadTimer = setTimeout(function() {245 console.log('streams::handleEvent - AppDotNetAPI - reloading, estimated new subs:', ref.pendingReloads)246 ref.loadSubscriptions()247 ref.pendingReloads = 0248 }, 100)249 }250 return251 }252 if (message.match(/^disconnect_/)) {253 var parts = message.split(/_/);254 var connectionId = parts[1];255 //console.log(connectionId, 'disconnected, write to cache');256 module.exports.cache.userStreamUpdate(connectionId, {257 connection_closed_at: new Date()258 }, function() {259 //console.log('userStream updated')260 })261 } else if (message.match(/^pong_/)){262 var parts = message.split(/_/);263 var connectionId = parts[1];264 var timestamp = parts[2];265 if (!module.exports.openPings[connectionId]) {266 // not really an error, just means we restarted...267 //console.log('streams::handleEvent - cant find any open pings for', connectionId);268 return;269 }270 var idx = module.exports.openPings[connectionId].indexOf(timestamp);271 if (idx) {272 module.exports.openPings[connectionId].splice(idx, 1);273 //console.log('streams::handleEvent -', connectionId, 'is connected');274 } else {275 console.error('streams::handleEvent - no openping for', timestamp, 'for', connectionId, 'we have', module.exports.openPings[connectionId]);276 }277 } else {278 console.error('streams::handleEvent - chan', channel, 'msg', message);279 }280 },281 // called in middleware282 handleSubscription: function(req, res) {283 var connId = req.query.connection_id;284 var accessToken = req.token;285 var connToken = null;286 var ref = this;287 function sendErrResponse(code, err) {288 var resObj={289 "meta": {290 "code": code,291 "error_message": err292 }293 };294 res.status(code).type('application/json').send(JSON.stringify(resObj));295 }296 //console.log('streams::handleSubscription - handling',req.path);297 this.redisClient.get("token_"+connId, function(err, reply) {298 if (!reply) {299 sendErrResponse(500, "no such connection")300 console.log('streams::handleSubscription - reply is empty', reply);301 return;302 }303 connToken = reply.toString();304 //console.log('connToken', connToken);305 if (connToken != accessToken) {306 console.log('streams::handleSubscription - connToken does not match accessToken', connToken, accessToken);307 sendErrResponse(401, "token mismatch")308 return;309 }310 ref.redisClient.get("autoDelete_"+connId, function(err, reply) {311 var autoDel = reply.toString(); // FIXME: look up in redis312 // convert string to token numeric id and get user id313 ref.cache.getAPIUserToken(accessToken, function(tokenObj, err) {314 //console.log('app::handleSubscription - tokenObj', tokenObj);315 if (err || !tokenObj) {316 sendErrResponse(401, "invalid token")317 console.log('streams::handleSubscription - token not found', accessToken, err);318 return;319 }320 ref.cache.findOrCreateUserStream(connId, tokenObj.id, tokenObj.userid, autoDel, function(userStream, err) {321 if (err || !userStream) {322 sendErrResponse(500, "cant create userStream")323 console.log('streams::handleSubscription - userStream could not be created', connId, tokenObj.id, tokenObj.userid, autoDel, err);324 return;325 }326 //console.log('app::handleSubscription - userStream', userStream);327 //console.log('app::handleSubscription - userStream.id', userStream.id);328 // FIXME: apply/adjust to all mount points329 // update auto_delete state330 var userStreamSubscriptionEndpoints = {331 //'/users/me/following': {},332 //'/users/me/followers': {},333 '/users/me/posts': {},334 //'/users/me/mentions': {},335 '/posts/stream': {},336 //'/posts/stream/unified': {},337 '/channels': {}, // (includes new messages for channels you're subscribed to)338 //'/users/me/files': {},339 //'/token': {}, // (includes updates for both the token and the user objects of the current user)340 //'/posts/:post_id/replies': {},341 //'/channels/:post_id/subscribers': {},342 '/channels/:post_id/messages': {},343 }344 var matchedPoint = req.path345 /*346 if (req.path.match(/^\/posts\/\d+\/replies/)) {347 matchedPoint = '/posts/:post_id/replies'348 } else349 if (req.path.match(/^\/channels\/\d+\/subscribers/)) {350 matchedPoint = '/channels/:post_id/subscribers'351 } else352 */353 if (req.path.match(/^\/channels\/\d+\/messages/)) {354 matchedPoint = '/channels/:post_id/messages'355 }356 var validEndpoint = userStreamSubscriptionEndpoints[matchedPoint]357 if (!validEndpoint) {358 console.log('app::handleSubscription - endpoint', matchedPoint, 'is not subscribable/implemented yet');359 sendErrResponse(500, "unsubscribable endpoint")360 return;361 }362 //console.log('app::handleSubscription - checking for subscribable endpoints', req.path, userStream);363 // check user_streamsubscriptions364 // make sure user_stream_id, stream doesn't already exist365 // if exists make sure params are updated366 // otherwise create it367 //console.log('app::handleSubscription - streamId', userStream.id);368 ref.cache.findOrCreateUserSubscription(userStream.id, req.path, JSON.stringify(req.apiParams), function(subscription, err) {369 if (err || !subscription) {370 console.log('streams::handleSubscription - subscription could not be created', userStream.id, req.path, err);371 sendErrResponse(500, "cant create subscription")372 return;373 }374 if (subscription.stream != req.path) {375 console.log('streams::handleSubscription - subscription could not be created, path doesnt match', subscription.stream, '!=', req.path);376 }377 //console.log('streams::handleSubscription - connection', connId, 'endpoint', req.path, 'subscription', subscription)378 // poke the dispatch engine to reload state from db379 //ref.loadSubscriptions();380 //console.log('streams::handleSubscription - publish');381 var data = {382 act: "sub",383 uid: tokenObj.userid,384 sid: userStream.id,385 sub: subscription386 }387 ref.redisClient.publish('AppDotNetAPI', JSON.stringify(data));388 var resObj={389 "meta": {390 "code": 200,391 "error_message": "Implemented"392 }393 };394 res.status(200).type('application/json').send(JSON.stringify(resObj));395 })396 });397 });398 });399 })400 }...

Full Screen

Full Screen

Subscriptions.js

Source:Subscriptions.js Github

copy

Full Screen

1import React, { useState, useEffect, useCallback } from 'react';2import { useDispatch, useSelector } from 'react-redux';3import Header from '../../../components/Header/Header';4import style from './Subscriptions.module.css';5import Button from '../../../components/UIcomponents/Button/Button';6import Payments from '../../../components/Payment/Payment';7import operathions from '../../../redux/user/userOperation';8import selector from '../../../redux/user/userSelector';9import Countdown from 'react-countdown';10export const changeColor = subscription => {11 switch (subscription) {12 case 'Noob':13 return style.Noob;14 case 'Basic':15 return style.Basic;16 case 'Standart':17 return style.Standart;18 case 'Premium':19 return style.Premium;20 case 'Ultra':21 return style.Ultra;22 default:23 return style.styleSubscpt;24 }25};26const Subscriptions = () => {27 const [plan, setPlan] = useState('');28 const [disabledBtn, setDisabled] = useState(false);29 const [disabledTimer, setTimer] = useState(false);30 const [showInfo, setShowInfo] = useState(false);31 const [sevenDays, setSevenDays] = useState(653440000);32 const dispatch = useDispatch();33 const subscription = useSelector(selector.getSubscription);34 const RegisterDate = useSelector(selector.getRegisterDate);35 let UserDateRegiste = new Date(RegisterDate);36 const normalDate = Date.parse(UserDateRegiste);37 const TimeLoop = Date.now() - normalDate;38 useEffect(() => {39 if (TimeLoop < sevenDays && subscription === 'Ultra') {40 setTimer(true);41 } else if (TimeLoop > sevenDays || subscription !== 'Ultra') {42 setTimer(false);43 }44 }, [TimeLoop, disabledTimer, dispatch, sevenDays, subscription]);45 const changeSubscription = useCallback(() => {46 dispatch(operathions.changeSubscription({ plan }));47 }, [dispatch, plan]);48 const handleSubscription = e => {49 setPlan(e.target.textContent);50 setDisabled(true);51 };52 const onTimerCompleted = useCallback(() => {53 dispatch(operathions.changeSubscription({ plan: 'Noob' }));54 }, [dispatch]);55 const changeAfterCoundown = () => {56 onTimerCompleted();57 };58 const pushSubsrpt = () => {59 changeSubscription();60 setDisabled(false);61 };62 const onMouseIn = () => {63 setShowInfo(true);64 };65 const onMouseLeave = () => {66 setShowInfo(false);67 };68 const timerStop = () => {69 setSevenDays(10000);70 onTimerCompleted();71 };72 return (73 <>74 <Header title="Подписки" />75 <div className={style.div}>76 <h2 className={style.header}>Тип подписки:</h2>77 <span className={changeColor(subscription)}>{subscription}</span>78 {disabledTimer && (79 <>80 <div className={style.timer}>81 <div>82 <span className={style.Text}>Day:</span>83 <span className={style.Text}>Hour:</span>84 <span className={style.Text}>Min:</span>85 <span className={style.Text}>Sec:</span>86 </div>87 <div>88 <Countdown89 date={normalDate + sevenDays}90 onComplete={changeAfterCoundown}91 />92 </div>93 </div>94 <button className={style.StopBtn} type="button" onClick={timerStop}>95 Stop96 </button>97 </>98 )}99 <div100 onMouseEnter={101 TimeLoop < sevenDays && subscription === 'Ultra'102 ? onMouseIn103 : undefined104 }105 onMouseLeave={106 TimeLoop < sevenDays && subscription === 'Ultra'107 ? onMouseLeave108 : undefined109 }110 >111 <div className={style.subscribe}>112 {showInfo && (113 <div className={style.Info}>114 Мы дарим Тебе на 7 дней нашу лучшую подписку! <br />115 -не хочешь ? - жми "Stop", или выбери другую!116 <br /> Желаем успехов в достижении Твоих целей!117 </div>118 )}119 <button120 type="button"121 className={122 disabledBtn && plan === 'Noob' ? style.test : style.btnNoob123 }124 onClick={handleSubscription}125 >126 Noob127 </button>128 <p className={style.color}> 30 дней — $4.99</p>129 </div>130 <div className={style.subscribe}>131 <button132 type="button"133 className={134 disabledBtn && plan === 'Basic' ? style.test : style.btnBasic135 }136 onClick={handleSubscription}137 >138 Basic139 </button>140 <p className={style.color}>141 1 месяц — $4.80 <span className={style.span}>- 3%</span>142 </p>143 </div>144 <div className={style.subscribe}>145 <button146 type="button"147 className={148 disabledBtn && plan === 'Standart'149 ? style.test150 : style.btnStandart151 }152 onClick={handleSubscription}153 >154 Standart155 </button>156 <p className={style.color}>157 3 месяца — $14.20 <span className={style.span}>- 5%</span>158 </p>159 </div>160 <div className={style.subscribe}>161 <button162 type="button"163 className={164 disabledBtn && plan === 'Premium'165 ? style.test166 : style.btnPremium167 }168 onClick={handleSubscription}169 >170 Premium171 </button>172 <p className={style.color}>173 6 месяцев — $27.84 <span className={style.span}>- 7%</span>174 </p>175 </div>176 <div className={style.subscribe}>177 <button178 type="button"179 className={180 disabledBtn && plan === 'Ultra' ? style.test : style.btnUltra181 }182 onClick={handleSubscription}183 >184 Ultra185 </button>186 <p className={style.color}>187 12 месяцев — $53.89 <span className={style.span}>- 10%</span>188 </p>189 </div>190 </div>191 <div className={style.position}>192 <Button193 type="button"194 label="Изменить подписку"195 handelClick={pushSubsrpt}196 />197 </div>198 </div>199 <Payments />200 </>201 );202};...

Full Screen

Full Screen

AppMenu.js

Source:AppMenu.js Github

copy

Full Screen

...84 }85 };86 if (isSubscribed) {87 const confirm = async () => {88 await handleSubscription();89 };90 setModal(91 <WarningModal92 close={closeModal}93 cancel={uninstall}94 confirm={confirm}95 text={t('Apps_Marketplace_Uninstall_Subscribed_App_Prompt')}96 confirmText={t('Apps_Marketplace_Modify_App_Subscription')}97 cancelText={t('Apps_Marketplace_Uninstall_Subscribed_App_Anyway')}98 />,99 );100 }101 setModal(102 <WarningModal close={closeModal} confirm={uninstall} text={t('Apps_Marketplace_Uninstall_App_Prompt')} confirmText={t('Yes')} />,...

Full Screen

Full Screen

add.js

Source:add.js Github

copy

Full Screen

1define(['knockout', 'jquery', 'uri', 'contexts/subscriptions', 'fastclick', 'notify'], function (ko, $, uri, subscriptionsContext, fastclick, notify) {2 3 var mapResult = function (result) {4 result.domain = uri(result.link).host;5 6 result.canSubscribe = ko.computed(function () {7 return subscriptionsContext.subscriptions().every(function (subscription) {8 return decodeURIComponent(subscription.xmlurl).toLowerCase() !== decodeURIComponent(result.url).toLowerCase();9 });10 });11 12 result.subscribe = function(category) {13 var self = this14 , selectedCategory = (self.newCategory().length > 0) ? self.newCategory() : category;15 16 self.subscribing(true);17 self.newCategory('');18 var handleSubscription = function (result) {19 if (result.added) {20 notify.success('successfully subscribed to feed');21 } else {22 notify.error('add', 'could not subscribe to feed');23 }24 25 self.subscribing(false);26 };27 28 subscriptionsContext.subscribe(self.url, selectedCategory, handleSubscription);29 };30 31 result.subscribing = ko.observable(false);32 result.newCategory = ko.observable('');33 34 result.newCategoryValid = ko.computed(function () {35 var self = this;36 return (self.newCategory().length > 0) &&37 (subscriptionsContext.categories().every(function (category) {38 return category.toLowerCase() != self.newCategory().toLowerCase();39 }));40 }, result);41 42 return result;43 };44 45 ViewModel = {46 activate : function () {47 48 },49 attached : function () {50 // prevent clicking the textbox from closing the menu51 $('.add').on('click', '.dropdown-menu input', function (evt) {52 evt.stopPropagation();53 });54 55 fastclick.attach(document.body);56 },57 deactivate : function () {58 this.results.removeAll();59 this.query('');60 this.resultQuery('');61 62 return false;63 },64 query : ko.observable(''),65 results : ko.observableArray(),66 loading : ko.observable(false),67 resultQuery : ko.observable(''),68 quickAdd : ko.observable(''),69 add : function () {70 var self = this;71 72 var handleSubscription = function (result) {73 console.log(result);74 if (result.added) {75 notify.success('successfully subscribed to feed');76 } else {77 notify.error('add', 'could not subscribe to feed');78 }79 };80 81 subscriptionsContext.subscribe(self.quickAdd(), 'main', handleSubscription);82 },83 search : function () {84 var self = this85 , searchUrl = 'https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&callback=?';86 87 if (self.query().length > 0) {88 self.loading(true);89 self.results.removeAll();90 91 $.getJSON(searchUrl, { q : self.query() })92 .fail(function (err) { console.log('alert here'); })93 .always(function () { 94 self.loading(false); 95 self.resultQuery(self.query());96 })97 .done(function (data) {98 if (data.responseStatus == 200) {99 var mapped = data.responseData.entries.map(mapResult);100 self.results(mapped); 101 } else {102 notify.error('add', 'could not retrieve feed results');103 } 104 });105 } else {106 notify.error('add', 'please enter a valid search query');107 } 108 },109 categories : ko.computed(function () {110 return subscriptionsContext.categories();111 }),112 navItems : [113 { hash : '/#/admin', icon : 'fa-cog', text: 'settings' } 114 ]115 };116 117 ViewModel.queryEntered = ko.computed(function () {118 return $.trim(this.query()).length > 0;119 }, ViewModel);120 121 return ViewModel;122 ...

Full Screen

Full Screen

local-signup.js

Source:local-signup.js Github

copy

Full Screen

1//Local User registration with passport-local2const User = require('../models/user');3const randomstring = require('randomstring');4const bcrypt = require('bcryptjs');5const LocalStrategy = require('passport-local').Strategy;6const HandleSubscription = require('../config/commonfunctions/handleSubscription');7// TODO: Connect the standardized validation error or success message with redux dispatch8// and share with the user9module.exports = new LocalStrategy({10 passReqToCallback: true, // allows us to pass back the entire request to the callback,11 passwordField: 'password',12 session: false,13 usernameField: 'email'14 }, (req, email, password, done) => {15 // Convert email to lowercase16 email = email.toLowerCase().trim();17 process.nextTick(function () {18 const handleSubscription = new HandleSubscription();19 // Check if the user exists20 User.findOne({ 'local_login.email': email}, (err, user) => {21 // if there are any errors, return the error22 if (err) {23 // Share the err status that occured due to mongoDB server or setup related issues24 return done(err, false);25 }26 // If user exists share a custom error27 if (user) {28 // Share user exists Error code29 const customErr = { "name": "MongoError", "code": 11000 };30 return done(customErr, false);31 }32 else {// For new user33 var verificationToken = randomstring.generate({ length: 64 });34 // Try to send an email to the user to see if email exists35 try {36 // Send subscription confirmation email to the user37 handleSubscription.sendEmail(req, email, verificationToken);38 // Create the user39 // tslint:disable-next-line:no-console40 console.log("NOW SAVE: ");41 var newUser = new User();42 const saltRounds = 10;43 // SET THE DATABASE(USER) DETAILS44 // Hash the password and record everything at the same time to the database due to ASYNC behavior45 handleSubscription.encryptUserInfo(req, done, email, password, verificationToken, saltRounds, newUser);46 } catch (subscriptionError) {47 // tslint:disable-next-line:no-console48 console.log("Subscription error: ", subscriptionError);49 return done(subscriptionError, false);50 }51 }52 });53 });...

Full Screen

Full Screen

newsletter.js

Source:newsletter.js Github

copy

Full Screen

1/**2 * Created by joakimcarlsten on 19/09/16.3 */4jQuery(document).ready(function($){5 'use strict';6 //Subscribe to newsletter7 var $subscribeButton = $('#subscribe-to-newsletter-button'),8 $loader = $('<div class="cover loader"><i class="fa fa-refresh fa-spin"></i></div>'),9 regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;10 if ($subscribeButton.length > 0) {11 $subscribeButton.on('click', handleSubscription);12 }13 function noop(event) {14 event.preventDefault();15 event.stopPropagation();16 return false;17 }18 function handleSubscription (e) {19 e.preventDefault();20 var $el = $(e.target);21 $el.blur();22 $el.append($loader);23 $el.off('click', handleSubscription);24 $el.on('click', noop);25 var $newsletterEmail = $('#newsletterEmail');26 //remove warnings and help-blocks27 $newsletterEmail.parent().removeClass('has-warning').find('.help-block').remove();28 //Check if empty email29 //TODO: Verify email address30 if (0 === $newsletterEmail.val().length || !regex.test($newsletterEmail.val())) {31 $newsletterEmail.parent().addClass('has-warning');32 $newsletterEmail.after('<span class="help-block">' + ajax_object.supply_email+ '</span>');33 $el.find($loader).remove();34 //re-enable event handlers35 $subscribeButton.off('click', noop);36 $subscribeButton.on('click', handleSubscription);37 } else {38 $.ajax( {39 method: 'post',40 url: ajax_object.ajax_url,41 dataType: 'json',42 data: {43 action: 'subscriberSubmit',44 email: $newsletterEmail.val()45 }46 }).done(function (result) {47 $(result.modal).modal();48 //re-enable event handlers49 $subscribeButton.off('click', noop);50 $subscribeButton.on('click', handleSubscription);51 $el.find($loader).remove();52 $newsletterEmail.val("");53 });54 }55 }...

Full Screen

Full Screen

webhook-notifications.js

Source:webhook-notifications.js Github

copy

Full Screen

...51/**52 *53 * @param webhookNotification54 */55function handleSubscription(app, webhookNotification) {56 _sendEmail(app, 'Braintree Subscription Notification', webhookNotification);57}58/**59 *60 * @param webhookNotification61 */62function handleTest(app, webhookNotification) {63 _sendEmail(app, 'Braintree Test Notification', webhookNotification);64}65function handleUnknown(app, webhookNotification) {66 _sendEmail(app, 'Braintree Unknown Notification', webhookNotification);67}68exports.handleDisbursement = handleDisbursement;69exports.handleDispute = handleDispute;...

Full Screen

Full Screen

Subscribe.js

Source:Subscribe.js Github

copy

Full Screen

1import React from "react";2import axios from "axios";3const Subscribe = () => {4 let [plan, setPlanCode] = React.useState("PLN_b42p2l4c09s24u4");5 let [email, setEmail] = React.useState("");6 let handleSubscription = async () => {7 // console.log(email);8 console.log({ plan, email, amount: 600 });9 let res = await axios.post("http://localhost:5000/paystack-post-handler", {10 paystackUrl: "https://api.paystack.co/transaction/initialize",11 data: {12 email,13 plan,14 amount: 600,15 },16 });17 console.log(res.data);18 };19 return (20 <div>21 <h1>Subscription</h1>22 <select23 onClick={(e) => {24 setPlanCode(e.target.value);25 }}26 >27 <option value={"PLN_b42p2l4c09s24u4"}>Monthly</option>28 <option value={"PLN_wcfw94769bj8fay"}>Annual</option>29 </select>30 <p>31 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia32 perferendis consequuntur eaque error illo magnam molestias quos33 explicabo sit, ipsum qui saepe quaerat repellendus hic maxime asperiores34 eligendi soluta laborum. Lorem ipsum dolor, sit amet consectetur35 adipisicing elit. Repellat fugiat sunt fugit suscipit earum ut36 voluptates incidunt ex? Repellat tenetur excepturi reprehenderit nihil37 culpa assumenda. Facere nemo fugit eum nulla.38 </p>39 <div>{plan}</div>40 <input41 type="text"42 name="email"43 onChange={(e) => setEmail(e.target.value)}44 />45 <button onClick={handleSubscription} className="btn btn-success col mt-5">46 Subscribe47 </button>48 </div>49 );50};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('handleSubscription', () => {2 cy.on('window:confirm', (str) => {3 expect(str).to.equal('Do you want to subscribe to the newsletter?');4 return true;5 });6});7describe('My First Test', () => {8 it('Does not do much!', () => {9 cy.contains('type').click();10 cy.get('.action-email')11 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.handleSubscription()2Cypress.Commands.add('handleSubscription', () => {3 cy.get('iframe[name="stripe_checkout_app"]').then(($iframe) => {4 const $body = $iframe.contents().find('body')5 cy.wrap($body)6 .find('button#submitButton')7 .click()8 })9})10Cypress.iframe() command11cy.handleSubscription()12Cypress.Commands.add('handleSubscription', () => {13 cy.get('iframe[name="stripe_checkout_app"]').then(($iframe) => {14 const $body = $iframe.contents().find('body')15 cy.iframe().then(iframeWindow => {16 cy.wrap(iframeWindow.document.body)17 .find('button#submitButton')18 .click()19 })20 })21})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('handleSubscription', (email) => {2 cy.get('#email').type(email)3 cy.get('#subscribe').click()4})5Cypress.Commands.add('handleSubscription', (email) => {6 cy.get('#email').type(email)7 cy.get('#subscribe').click()8})9Cypress.Commands.add('handleSubscription', (email) => {10 cy.get('#email').type(email)11 cy.get('#subscribe').click()12})13Cypress.Commands.add('handleSubscription', (email) => {14 cy.get('#email').type(email)15 cy.get('#subscribe').click()16})17Cypress.Commands.add('handleSubscription', (email) => {18 cy.get('#email').type(email)19 cy.get('#subscribe').click()20})21Cypress.Commands.add('handleSubscription', (email) => {22 cy.get('#email').type(email)23 cy.get('#subscribe').click()24})25Cypress.Commands.add('handleSubscription', (email) => {26 cy.get('#email').type(email)27 cy.get('#subscribe').click()28})29Cypress.Commands.add('handleSubscription', (email) => {30 cy.get('#email').type(email)31 cy.get('#subscribe').click()32})33Cypress.Commands.add('handleSubscription', (email) => {34 cy.get('#email').type(email)35 cy.get('#subscribe').click()36})37Cypress.Commands.add('handleSubscription', (email) => {38 cy.get('#email').type(email)39 cy.get('#subscribe').click()40})41Cypress.Commands.add('handleSubscription', (email) => {42 cy.get('#email').type(email)43 cy.get('#subscribe').click

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('Test', function() {3 cy.get('.gLFyf').type('cypress')4 cy.get('.FPdoLc > center > .gNO89b').click()5 cy.get(':nth-child(1) > .rc > .r > a > h3').click()6 cy.get('.docs-header-nav > :nth-child(1) > .docs-header-nav-link').click()7 cy.get('.docs-header-nav > :nth-child(2) > .docs-header-nav-link').click()8 cy.get('.docs-header-nav > :nth-child(3) > .docs-header-nav-link').click()9 cy.get('.docs-header-nav > :nth-child(4) > .docs-header-nav-link').click()10 cy.get('.docs-header-nav > :nth-child(5) > .docs-header-nav-link').click()11 cy.get('.docs-header-nav > :nth-child(6) > .docs-header-nav-link').click()12 cy.get('.docs-header-nav > :nth-child(7) > .docs-header-nav-link').click()13 cy.get('.docs-header-nav > :nth-child(8) > .docs-header-nav-link').click()14 cy.get('.docs-header-nav > :nth-child(9) > .docs-header-nav-link').click()15 cy.get('.docs-header-nav > :nth-child(10) > .docs-header-nav-link').click()16 cy.get('.docs-header-nav > :nth-child(11) > .docs-header-nav-link').click()17 cy.get('.docs-header-nav > :nth-child(12) > .docs-header-nav-link').click()18 cy.get('.docs-header-nav > :nth-child(13) > .docs-header-nav-link').click()19 cy.get('.docs-header-nav > :nth-child(14) > .docs-header-nav-link').click()20 cy.get('.docs-header-nav > :nth-child(15) > .docs-header-nav-link').click()21 cy.get('.docs-header-nav > :nth-child(16) > .docs-header-nav-link').click()22 cy.get('.docs-header-nav > :nth-child(17) > .docs-header-nav-link').click()23 cy.get('.docs-header-nav > :nth-child(18) > .docs-header-nav-link').click()

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.handleSubscription = (callback, timeout = 30000) => {2 let subscription = null;3 const unsubscribe = () => {4 if (subscription) {5 subscription.unsubscribe();6 }7 };8 return new Promise((resolve, reject) => {9 const timeoutHandle = setTimeout(() => {10 unsubscribe();11 reject(new Error('Timeout'));12 }, timeout);13 subscription = callback((data) => {14 clearTimeout(timeoutHandle);15 unsubscribe();16 resolve(data);17 });18 });19};20describe('Subscribe', () => {21 it('should receive a message', () => {22 cy.visit('/');23 cy.get('#subscribe').click();24 cy.handleSubscription((handler) => {25 window.addEventListener('message', (event) => {26 handler(event.data);27 });28 }).then((data) => {29 expect(data).to.equal('Hello World!');30 });31 });32});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('test', () => {3 cy.handleSubscription('mySubscription', (msg) => {4 });5 });6});7Cypress.Commands.add('handleSubscription', (name, callback) => {8 cy.window().then((win) => {9 win.socket.on(name, callback);10 });11});12import './commands';13{14}15module.exports = (on, config) => {16 on('task', {17 socket: (options) => {18 if (options.action === 'connect') {19 const io = require('socket.io-client');20 });21 socket.on('connect', () => {22 console.log('Connected to websocket');23 });24 socket.on('error', (err) => {25 console.log('Error connecting to websocket', err);26 });27 socket.on('disconnect', () => {28 console.log('Disconnected from websocket');29 });30 cy.state('window').socket = socket;31 } else if (options.action === 'disconnect') {32 cy.state('window').socket.disconnect();33 }34 },35 });36};37describe('Testing socket', () => {38 it('Test', () => {39 cy.task('socket', { action: 'connect' });40 cy.handleSubscription('mySubscription', (msg) => {41 });42 cy.task('socket', { action: 'disconnect' });43 });44});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.handleSubscription();2Cypress.Commands.add('handleSubscription', () => {3});4Cypress.Commands.add('handleSubscription', () => {5});6Cypress.Commands.add('handleSubscription', () => {7});

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('handleSubscription', {prevSubject: 'optional'}, (subject, options) => {2})3import './commands'4module.exports = (on, config) => {5}6describe('My Test', () => {7 it('should do something', () => {8 })9})10{

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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