Best JavaScript code snippet using redwood
Notifications.js
Source:Notifications.js
1const express = require('express')2const notifications = express.Router()3const mongoose = require('mongoose')4const protectRoute = require('../securityToken/verifyToken')5const LogService = require('../logService/logService')6const userSchema = require('../models/Users')7const notificationSchema = require('../models/Notifications')8const cors = require('cors')9const connect = require('../mongoConnection/conectionInstances')10notifications.use(cors())11//Api que busca todas las notificaciones (Ingreso: Nullo) -- Api that search all the notifications (Input: Null)12notifications.get('/', protectRoute, async (req, res) => {13 const database = req.headers['x-database-connect'];14 15 const Notification = connect.useDb(database).model('notifications', notificationSchema)16 try{17 const getnotifications = await Notification.find()18 if (getnotifications.length > 0 ) {19 res.json({status: 'ok', data: getnotifications, token: req.requestToken})20 }else{21 res.json({status: 'nothing found'})22 }23 }catch(err){24 const Log = new LogService(25 req.headers.host, 26 req.body, 27 req.params, 28 err, 29 req.requestToken, 30 req.headers['x-database-connect'], 31 req.route32 )33 Log.createLog()34 .then(dataLog => {35 res.send('failed api with error, '+ dataLog.error)36 })37 }38})39//Final de la api. (Retorna: Notificaciones) -- Api end. (Return: Notifications)40//-------------------------------------------------------------------------41//Api que busca todas las notificaciones que no ha visto un usuario (Ingreso: ObjectId del usuario) -- Api that search all the unview notifications for a user (Input: User´s ObjectId)42notifications.get('/noviews/:id', protectRoute, async (req, res) => {43 const database = req.headers['x-database-connect'];44 const Notification = connect.useDb(database).model('notifications', notificationSchema)45 const User = connect.useDb(database).model('users', userSchema)46 var validLimited = false47 try{48 const findUser = await User.findById(req.params.id)49 if(findUser){50 if(findUser.notificationLimited && findUser.notificationLimited == true){51 validLimited = true52 }53 }54 if(validLimited){55 try{56 const getnotifications = await Notification.find({employeId: findUser.linkLender}).sort({createdAt: -1}).limit(150)57 58 if (getnotifications.length > 0 ) {59 60 let onlyYours = []61 for (let i = 0; i < getnotifications.length; i++) {62 const elementN = getnotifications[i];63 let inps = true64 for (let e = 0; e < getnotifications[i].views.length; e++) {65 const element = getnotifications[i].views[e];66 if (element == req.params.id) {67 inps = false68 break69 }70 }71 if (inps) {72 onlyYours.push(elementN)73 }74 }75 76 res.json({status: 'ok', data: onlyYours, token: req.requestToken})77 }else{78 res.json({status: 'nothing found'})79 }80 }catch(err){81 const Log = new LogService(82 req.headers.host, 83 req.body, 84 req.params, 85 err, 86 req.requestToken, 87 req.headers['x-database-connect'], 88 req.route89 )90 Log.createLog()91 .then(dataLog => {92 res.send('failed api with error, '+ dataLog.error)93 })94 }95 }else{96 try{97 const getnotifications = await Notification.find().sort({createdAt: -1}).limit(150)98 99 if (getnotifications.length > 0 ) {100 101 let onlyYours = []102 for (let i = 0; i < getnotifications.length; i++) {103 const elementN = getnotifications[i];104 let inps = true105 for (let e = 0; e < getnotifications[i].views.length; e++) {106 const element = getnotifications[i].views[e];107 if (element == req.params.id) {108 inps = false109 break110 }111 }112 if (inps) {113 onlyYours.push(elementN)114 }115 }116 117 res.json({status: 'ok', data: onlyYours, token: req.requestToken})118 }else{119 res.json({status: 'nothing found'})120 }121 }catch(err){122 const Log = new LogService(123 req.headers.host, 124 req.body, 125 req.params, 126 err, 127 req.requestToken, 128 req.headers['x-database-connect'], 129 req.route130 )131 Log.createLog()132 .then(dataLog => {133 res.send('failed api with error, '+ dataLog.error)134 })135 }136 }137 138 }catch(err){139 console.log(err)140 }141 142})143//Final de la api. (Retorna: Notificaciones) -- Api end. (Return: Notifications)144//-------------------------------------------------------------------------145//Api que registra que un usuario vio sus notificaciones (Ingreso: ObjectId del usuario) -- Api that register that an user view its notifications (Input: User´s ObjectId)146notifications.get('/validateviews/:id', protectRoute, async (req, res) => {147 const database = req.headers['x-database-connect'];148 149 const User = connect.useDb(database).model('users', userSchema)150 const Notification = connect.useDb(database).model('notifications', notificationSchema)151 var validLimited = false152 try{153 const findUser = await User.findById(req.params.id)154 if(findUser){155 if(findUser.notificationLimited && findUser.notificationLimited == true){156 validLimited = true157 }158 }159 if(validLimited){160 Notification.find({employeId: findUser.linkLender}).sort({createdAt: -1}).limit(150)161 .then(getNotifications => {162 if (getNotifications) { 163 let onlyYours = []164 for (let i = 0; i < getNotifications.length; i++) {165 const elementN = getNotifications[i];166 let inps = true167 for (let e = 0; e < getNotifications[i].views.length; e++) {168 const element = getNotifications[i].views[e];169 if (element == req.params.id) {170 inps = false171 }172 }173 if (inps) {174 onlyYours.push(elementN)175 Notification.findByIdAndUpdate(elementN._id, {$push: { views: req.params.id}})176 .then(ready => {})177 }178 }179 res.json({status: 'ok', data: onlyYours, token: req.requestToken})180 }else{181 res.json({status: 'nothing found'})182 }183 }).catch(err=>{184 const Log = new LogService(185 req.headers.host, 186 req.body, 187 req.params, 188 err, 189 req.requestToken, 190 req.headers['x-database-connect'], 191 req.route192 )193 Log.createLog()194 .then(dataLog => {195 res.send('failed api with error, '+ dataLog.error)196 })197 })198 }else{199 Notification.find().sort({createdAt: -1}).limit(150)200 .then(getNotifications => {201 if (getNotifications) { 202 let onlyYours = []203 for (let i = 0; i < getNotifications.length; i++) {204 const elementN = getNotifications[i];205 let inps = true206 for (let e = 0; e < getNotifications[i].views.length; e++) {207 const element = getNotifications[i].views[e];208 if (element == req.params.id) {209 inps = false210 }211 }212 if (inps) {213 onlyYours.push(elementN)214 Notification.findByIdAndUpdate(elementN._id, {$push: { views: req.params.id}})215 .then(ready => {})216 }217 }218 res.json({status: 'ok', data: onlyYours, token: req.requestToken})219 }else{220 res.json({status: 'nothing found'})221 }222 }).catch(err=>{223 const Log = new LogService(224 req.headers.host, 225 req.body, 226 req.params, 227 err, 228 req.requestToken, 229 req.headers['x-database-connect'], 230 req.route231 )232 Log.createLog()233 .then(dataLog => {234 res.send('failed api with error, '+ dataLog.error)235 })236 })237 }238 } 239 catch(err){240 console.log(err)241 } 242 243})244//Final de la api. (Retorna: Notificaciones) -- Api end. (Return: Notifications)245//-------------------------------------------------------------------------246//Api que busca todas las notificaciones (max: 500) (Ingreso: Nullo) -- Api that search all the notifications (max: 500) (Input: Null)247notifications.get('/getall/:id', protectRoute, async (req, res) => {248 const database = req.headers['x-database-connect'];249 250 const User = connect.useDb(database).model('users', userSchema)251 const Notification = connect.useDb(database).model('notifications', notificationSchema)252 var validLimited = false253 try{254 const findUser = await User.findById(req.params.id)255 if(findUser){256 if(findUser.notificationLimited && findUser.notificationLimited == true){257 validLimited = true258 }259 }260 if (validLimited) {261 try{262 const getnotifications = await Notification.find({employeId: findUser.linkLender}).sort({createdAt: -1}).limit(500)263 if (getnotifications.length > 0 ) {264 res.json({status: 'ok', data: getnotifications, token: req.requestToken})265 }else{266 res.json({status: 'nothing found'})267 }268 }catch(err){269 const Log = new LogService(270 req.headers.host, 271 req.body, 272 req.params, 273 err, 274 req.requestToken, 275 req.headers['x-database-connect'], 276 req.route277 )278 Log.createLog()279 .then(dataLog => {280 res.send('failed api with error, '+ dataLog.error)281 })282 }283 }else{284 try{285 const getnotifications = await Notification.find().sort({createdAt: -1}).limit(500)286 if (getnotifications.length > 0 ) {287 res.json({status: 'ok', data: getnotifications, token: req.requestToken})288 }else{289 res.json({status: 'nothing found'})290 }291 }catch(err){292 const Log = new LogService(293 req.headers.host, 294 req.body, 295 req.params, 296 err, 297 req.requestToken, 298 req.headers['x-database-connect'], 299 req.route300 )301 Log.createLog()302 .then(dataLog => {303 res.send('failed api with error, '+ dataLog.error)304 })305 }306 }307 }catch(err){308 console.log(err)309 } 310 311})312//Final de la api. (Retorna: Notificaciones) -- Api end. (Return: Notifications)313//-------------------------------------------------------------------------314//Api que crea una nueva notificación (Ingreso: branch, userName, userImg, detail, link) -- Api that create a new notification (Input: branch, userName, userImg, detail, link)315notifications.post('/', async (req, res) => {316 const database = req.headers['x-database-connect'];317 318 const Notification = connect.useDb(database).model('notifications', notificationSchema)319 const dataNotify = {320 branch: req.body.branch,321 userName: req.body.userName,322 userImg: req.body.userImage,323 employeId: req.body.employeId,324 detail: req.body.detail,325 link: req.body.link326 }327 try{328 const register = await Notification.create(dataNotify)329 if (register) {330 res.json({status: 'ok', data: register})331 }332 }catch(err){333 const Log = new LogService(334 req.headers.host, 335 req.body, 336 req.params, 337 err, 338 req.requestToken, 339 req.headers['x-database-connect'], 340 req.route341 )342 Log.createLog()343 .then(dataLog => {344 res.send('failed api with error, '+ dataLog.error)345 })346 }347})348//Final de la api. (Retorna: Datos de la notificacion) -- Api end. (Return: Notification´s data)...
notification_dropdown_view_spec.js
Source:notification_dropdown_view_spec.js
1describe('app.views.NotificationDropdown', function() {2 beforeEach(function (){3 spec.loadFixture('notifications');4 this.header = new app.views.Header();5 $("header").prepend(this.header.el);6 this.header.render();7 this.view = new app.views.NotificationDropdown({el: '#notification_badge'});8 });9 context('showDropdown', function(){10 it('Calls resetParam()', function(){11 spyOn(this.view, 'resetParams');12 this.view.showDropdown();13 expect(this.view.resetParams).toHaveBeenCalled();14 });15 it('Changes CSS', function(){16 this.view.showDropdown();17 expect($('#notification_dropdown').css('display')).toBe('block');18 });19 it('Calls getNotifications()', function(){20 spyOn(this.view, 'getNotifications');21 this.view.showDropdown();22 expect(this.view.getNotifications).toHaveBeenCalled();23 });24 });25 context('dropdownScroll', function(){26 it('Calls getNotifications if is at the bottom and has more notifications to load', function(){27 this.view.isBottom = function(){ return true; };28 this.view.hasMoreNotifs = true;29 spyOn(this.view, 'getNotifications');30 this.view.dropdownScroll();31 expect(this.view.getNotifications).toHaveBeenCalled();32 });33 it("Doesn't call getNotifications if is not at the bottom", function(){34 this.view.isBottom = function(){ return false; };35 this.view.hasMoreNotifs = true;36 spyOn(this.view, 'getNotifications');37 this.view.dropdownScroll();38 expect(this.view.getNotifications).not.toHaveBeenCalled();39 });40 it("Doesn't call getNotifications if is not at the bottom", function(){41 this.view.isBottom = function(){ return true; };42 this.view.hasMoreNotifs = false;43 spyOn(this.view, 'getNotifications');44 this.view.dropdownScroll();45 expect(this.view.getNotifications).not.toHaveBeenCalled();46 });47 });48 context('getNotifications', function(){49 it('Has more notifications', function(){50 var response = ['', '', '', '', ''];51 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback(response); });52 this.view.getNotifications();53 expect(this.view.hasMoreNotifs).toBe(true);54 });55 it('Has no more notifications', function(){56 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback([]); });57 this.view.getNotifications();58 expect(this.view.hasMoreNotifs).toBe(false);59 });60 it('Correctly sets the next page', function(){61 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback([]); });62 expect(typeof this.view.nextPage).toBe('undefined');63 this.view.getNotifications();64 expect(this.view.nextPage).toBe(3);65 });66 it('Increase the page count', function(){67 var response = ['', '', '', '', ''];68 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback(response); });69 this.view.getNotifications();70 expect(this.view.nextPage).toBe(3);71 this.view.getNotifications();72 expect(this.view.nextPage).toBe(4);73 });74 it('Calls renderNotifications()', function(){75 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback([]); });76 spyOn(this.view, 'renderNotifications');77 this.view.getNotifications();78 expect(this.view.renderNotifications).toHaveBeenCalled();79 });80 it('Adds the notifications to this.notifications', function(){81 var response = ['', '', '', '', ''];82 this.view.notifications.length = 0;83 spyOn($, 'getJSON').and.callFake(function(url, callback){ callback(response); });84 this.view.getNotifications();85 expect(this.view.notifications).toEqual(response);86 });87 });88 context('renderNotifications', function(){89 it('Removes the previous notifications', function(){90 this.view.dropdownNotifications.append('<div class="media stream_element">Notification</div>');91 expect(this.view.dropdownNotifications.find('.media.stream_element').length).toBe(1);92 this.view.renderNotifications();93 expect(this.view.dropdownNotifications.find('.media.stream_element').length).toBe(0);94 });95 it('Calls hideAjaxLoader()', function(){96 spyOn(this.view, 'hideAjaxLoader');97 this.view.renderNotifications();98 expect(this.view.hideAjaxLoader).toHaveBeenCalled();99 });100 });...
getNotifications.spec.ts
Source:getNotifications.spec.ts
1/// <reference types="Cypress" />2import {query} from 'gql-query-builder';3import {unauthorizedErrorObject} from '../../../fixtures/api-test/helper-objects/response-objects';4let apierror = unauthorizedErrorObject(5 `getNotifications`,6 'Unauthorized',7 'Not Authorized to access getNotifications on type NotificationsConnection',8 1,9 3110);11describe(`Security Test cases for getNotifications`, () => {12 it(`C179950 : Verify that an error is returned when hitting getNotifications API for the group with the authtoken of user that is not an admin`, function () {13 const appSyncUrl = Cypress.env(`developAppSyncUrl`);14 const getNotifications = query({15 operation: `getNotifications`,16 variables: {17 forUserId: {value: this.userDataJson.postDetails.userId, required: true}18 },19 fields: [`items{inAppTitle}`]20 });21 // @ts-ignore22 cy.api({23 method: `POST`,24 url: appSyncUrl,25 headers: {26 authorization: this.tokensJson.groupToken27 },28 body: getNotifications29 })30 .its(`body`)31 .should(`deep.eq`, apierror);32 });33 it(`C179950 : Verify that an error is returned when hitting getNotifications API for the group with the authtoken of user that is not an admin`, function () {34 const appSyncUrl = Cypress.env(`developAppSyncUrl`);35 const getNotifications = query({36 operation: `getNotifications`,37 variables: {38 forUserId: {value: this.userDataJson.postDetails.userId, required: true}39 },40 fields: [`items{inAppTitle}`]41 });42 // @ts-ignore43 cy.api({44 method: `POST`,45 url: appSyncUrl,46 headers: {47 authorization: this.tokensJson.brandAdminToken48 },49 body: getNotifications50 })51 .its(`body`)52 .should(`deep.eq`, apierror);53 });...
Using AI Code Generation
1var redwood = require('redwood');2var service = new redwood.Service();3service.GetNotifications(1, 1, 0, 0, function (err, notifications) {4 if (err) {5 console.log(err);6 } else {7 console.log(notifications);8 }9});10GetNotification(id, callback)11var redwood = require('redwood');12var service = new redwood.Service();13service.GetNotification(1, function (err, notification) {14 if (err) {15 console.log(err);16 } else {17 console.log(notification);18 }19});20GetNotificationCount(userId, callback)21var redwood = require('redwood');22var service = new redwood.Service();23service.GetNotificationCount(1, function (err, count) {24 if (err) {25 console.log(err);26 } else {27 console.log(count);28 }29});30GetUnreadNotificationCount(userId, callback)31var redwood = require('redwood');32var service = new redwood.Service();33service.GetUnreadNotificationCount(1, function (err, count) {
Using AI Code Generation
1const { GetNotifications } = require("./redwood_api.js");2async function test() {3 let notifications = await GetNotifications();4 console.log(notifications);5}6test();
Using AI Code Generation
1var redwood = require('redwood');2var request = new redwood.GetNotificationsRequest();3request.setLastNotificationId(0);4request.setLastNotificationTime(0);5request.setUserId(1);6request.setNotificationTypes([redwood.NotificationType.FRIEND_REQUEST, redwood.NotificationType.FRIEND_REQUEST_ACCEPTED]);7redwoodClient.getNotifications(request, function(err, response) {8 if (err) {9 console.log(err);10 } else {11 console.log(response);12 }13});
Using AI Code Generation
1var redwood = require('redwood');2client.GetNotifications(function(err, data) {3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var redwood = require('redwood');10client.GetNotification(1, function(err, data) {11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});17var redwood = require('redwood');18client.GetNotificationTypes(function(err, data) {19 if (err) {20 console.log(err);21 } else {22 console.log(data);23 }24});25var redwood = require('redwood');26client.GetNotificationType(1, function(err, data) {27 if (err) {28 console.log(err);29 } else {30 console.log(data);31 }32});33var redwood = require('redwood');34client.GetUserNotifications(1, function(err, data) {35 if (err) {36 console.log(err);37 } else {38 console.log(data);39 }40});41#### new Client(host, username, password)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!