Snippets Collections
import { useEffect, useMemo, useRef, useState } from 'react'
import { useWeb3React } from '@web3-react/core'
import Web3 from 'web3'

import { defaultEVMNetworkId } from '@contracts/networks'

import { web3NoAccountInstances } from '@utils/web3'

export const useWeb3 = () => {
  const { library, chainId } = useWeb3React()
  const web3NoAccount = useMemo(
    () =>
      web3NoAccountInstances[
        chainId ? chainId.toString() : defaultEVMNetworkId
      ],
    [chainId]
  )
  const refChainId = useRef(chainId)
  const refWeb3 = useRef(library)
  const [web3, setweb3] = useState(library ? new Web3(library) : web3NoAccount)

  useEffect(() => {
    if (library !== refWeb3.current || chainId !== refChainId.current) {
      setweb3(library ? new Web3(library) : web3NoAccount)
      refWeb3.current = library
      refChainId.current = chainId
    }
  }, [chainId, library, web3NoAccount])

  return web3
}
import { isMobile } from 'react-device-detect'
import { useWeb3 } from '@firestarter-private/firestarter-library'
import { UnsupportedChainIdError, useWeb3React } from '@web3-react/core'

import { injected, walletconnect } from '@/connectors'

export const useWalletConnect = (): { onClickWallet: () => void } => {
  const web3 = useWeb3()
  const { activate } = useWeb3React()

  const onClickWallet = () => {
    if (isMobile) {
      // if the connector is walletconnect and the user has already tried to connect, manually reset the connector
      if (
        // @ts-ignore
        walletconnect.walletConnectProvider?.wc?.uri
      ) {
        walletconnect.walletConnectProvider = undefined
      }
      activate(walletconnect, undefined, true).catch((error) => {
        if (error instanceof UnsupportedChainIdError) {
          activate(walletconnect) // a little janky...can't use setError because the connector isn't set
        }
      })
      // @ts-ignore
      web3.setProvider(window.ethereum)
    } else {
      activate(injected)
    }
  }

  return { onClickWallet }
}
DROP DATABASE IF EXISTS `sql_invoicing`;
CREATE DATABASE `sql_invoicing`; 
USE `sql_invoicing`;

SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;

CREATE TABLE `payment_methods` (
  `payment_method_id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payment_methods` VALUES (1,'Credit Card');
INSERT INTO `payment_methods` VALUES (2,'Cash');
INSERT INTO `payment_methods` VALUES (3,'PayPal');
INSERT INTO `payment_methods` VALUES (4,'Wire Transfer');

CREATE TABLE `clients` (
  `client_id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `phone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `clients` VALUES (1,'Vinte','3 Nevada Parkway','Syracuse','NY','315-252-7305');
INSERT INTO `clients` VALUES (2,'Myworks','34267 Glendale Parkway','Huntington','WV','304-659-1170');
INSERT INTO `clients` VALUES (3,'Yadel','096 Pawling Parkway','San Francisco','CA','415-144-6037');
INSERT INTO `clients` VALUES (4,'Kwideo','81674 Westerfield Circle','Waco','TX','254-750-0784');
INSERT INTO `clients` VALUES (5,'Topiclounge','0863 Farmco Road','Portland','OR','971-888-9129');

CREATE TABLE `invoices` (
  `invoice_id` int(11) NOT NULL,
  `number` varchar(50) NOT NULL,
  `client_id` int(11) NOT NULL,
  `invoice_total` decimal(9,2) NOT NULL,
  `payment_total` decimal(9,2) NOT NULL DEFAULT '0.00',
  `invoice_date` date NOT NULL,
  `due_date` date NOT NULL,
  `payment_date` date DEFAULT NULL,
  PRIMARY KEY (`invoice_id`),
  KEY `FK_client_id` (`client_id`),
  CONSTRAINT `FK_client_id` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `invoices` VALUES (1,'91-953-3396',2,101.79,0.00,'2019-03-09','2019-03-29',NULL);
INSERT INTO `invoices` VALUES (2,'03-898-6735',5,175.32,8.18,'2019-06-11','2019-07-01','2019-02-12');
INSERT INTO `invoices` VALUES (3,'20-228-0335',5,147.99,0.00,'2019-07-31','2019-08-20',NULL);
INSERT INTO `invoices` VALUES (4,'56-934-0748',3,152.21,0.00,'2019-03-08','2019-03-28',NULL);
INSERT INTO `invoices` VALUES (5,'87-052-3121',5,169.36,0.00,'2019-07-18','2019-08-07',NULL);
INSERT INTO `invoices` VALUES (6,'75-587-6626',1,157.78,74.55,'2019-01-29','2019-02-18','2019-01-03');
INSERT INTO `invoices` VALUES (7,'68-093-9863',3,133.87,0.00,'2019-09-04','2019-09-24',NULL);
INSERT INTO `invoices` VALUES (8,'78-145-1093',1,189.12,0.00,'2019-05-20','2019-06-09',NULL);
INSERT INTO `invoices` VALUES (9,'77-593-0081',5,172.17,0.00,'2019-07-09','2019-07-29',NULL);
INSERT INTO `invoices` VALUES (10,'48-266-1517',1,159.50,0.00,'2019-06-30','2019-07-20',NULL);
INSERT INTO `invoices` VALUES (11,'20-848-0181',3,126.15,0.03,'2019-01-07','2019-01-27','2019-01-11');
INSERT INTO `invoices` VALUES (13,'41-666-1035',5,135.01,87.44,'2019-06-25','2019-07-15','2019-01-26');
INSERT INTO `invoices` VALUES (15,'55-105-9605',3,167.29,80.31,'2019-11-25','2019-12-15','2019-01-15');
INSERT INTO `invoices` VALUES (16,'10-451-8824',1,162.02,0.00,'2019-03-30','2019-04-19',NULL);
INSERT INTO `invoices` VALUES (17,'33-615-4694',3,126.38,68.10,'2019-07-30','2019-08-19','2019-01-15');
INSERT INTO `invoices` VALUES (18,'52-269-9803',5,180.17,42.77,'2019-05-23','2019-06-12','2019-01-08');
INSERT INTO `invoices` VALUES (19,'83-559-4105',1,134.47,0.00,'2019-11-23','2019-12-13',NULL);

CREATE TABLE `payments` (
  `payment_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `amount` decimal(9,2) NOT NULL,
  `payment_method` tinyint(4) NOT NULL,
  PRIMARY KEY (`payment_id`),
  KEY `fk_client_id_idx` (`client_id`),
  KEY `fk_invoice_id_idx` (`invoice_id`),
  KEY `fk_payment_payment_method_idx` (`payment_method`),
  CONSTRAINT `fk_payment_client` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_invoice` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`invoice_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_payment_method` FOREIGN KEY (`payment_method`) REFERENCES `payment_methods` (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payments` VALUES (1,5,2,'2019-02-12',8.18,1);
INSERT INTO `payments` VALUES (2,1,6,'2019-01-03',74.55,1);
INSERT INTO `payments` VALUES (3,3,11,'2019-01-11',0.03,1);
INSERT INTO `payments` VALUES (4,5,13,'2019-01-26',87.44,1);
INSERT INTO `payments` VALUES (5,3,15,'2019-01-15',80.31,1);
INSERT INTO `payments` VALUES (6,3,17,'2019-01-15',68.10,1);
INSERT INTO `payments` VALUES (7,5,18,'2019-01-08',32.77,1);
INSERT INTO `payments` VALUES (8,5,18,'2019-01-08',10.00,2);


DROP DATABASE IF EXISTS `sql_store`;
CREATE DATABASE `sql_store`;
USE `sql_store`;

CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


CREATE TABLE `shippers` (
  `shipper_id` smallint(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`shipper_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `shippers` VALUES (1,'Hettinger LLC');
INSERT INTO `shippers` VALUES (2,'Schinner-Predovic');
INSERT INTO `shippers` VALUES (3,'Satterfield LLC');
INSERT INTO `shippers` VALUES (4,'Mraz, Renner and Nolan');
INSERT INTO `shippers` VALUES (5,'Waters, Mayert and Prohaska');


CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `birth_date` date DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `points` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `customers` VALUES (1,'Babara','MacCaffrey','1986-03-28','781-932-9754','0 Sage Terrace','Waltham','MA',2273);
INSERT INTO `customers` VALUES (2,'Ines','Brushfield','1986-04-13','804-427-9456','14187 Commercial Trail','Hampton','VA',947);
INSERT INTO `customers` VALUES (3,'Freddi','Boagey','1985-02-07','719-724-7869','251 Springs Junction','Colorado Springs','CO',2967);
INSERT INTO `customers` VALUES (4,'Ambur','Roseburgh','1974-04-14','407-231-8017','30 Arapahoe Terrace','Orlando','FL',457);
INSERT INTO `customers` VALUES (5,'Clemmie','Betchley','1973-11-07',NULL,'5 Spohn Circle','Arlington','TX',3675);
INSERT INTO `customers` VALUES (6,'Elka','Twiddell','1991-09-04','312-480-8498','7 Manley Drive','Chicago','IL',3073);
INSERT INTO `customers` VALUES (7,'Ilene','Dowson','1964-08-30','615-641-4759','50 Lillian Crossing','Nashville','TN',1672);
INSERT INTO `customers` VALUES (8,'Thacher','Naseby','1993-07-17','941-527-3977','538 Mosinee Center','Sarasota','FL',205);
INSERT INTO `customers` VALUES (9,'Romola','Rumgay','1992-05-23','559-181-3744','3520 Ohio Trail','Visalia','CA',1486);
INSERT INTO `customers` VALUES (10,'Levy','Mynett','1969-10-13','404-246-3370','68 Lawn Avenue','Atlanta','GA',796);


CREATE TABLE `order_statuses` (
  `order_status_id` tinyint(4) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`order_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_statuses` VALUES (1,'Processed');
INSERT INTO `order_statuses` VALUES (2,'Shipped');
INSERT INTO `order_statuses` VALUES (3,'Delivered');


CREATE TABLE `orders` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `order_date` date NOT NULL,
  `status` tinyint(4) NOT NULL DEFAULT '1',
  `comments` varchar(2000) DEFAULT NULL,
  `shipped_date` date DEFAULT NULL,
  `shipper_id` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`order_id`),
  KEY `fk_orders_customers_idx` (`customer_id`),
  KEY `fk_orders_shippers_idx` (`shipper_id`),
  KEY `fk_orders_order_statuses_idx` (`status`),
  CONSTRAINT `fk_orders_customers` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_order_statuses` FOREIGN KEY (`status`) REFERENCES `order_statuses` (`order_status_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_shippers` FOREIGN KEY (`shipper_id`) REFERENCES `shippers` (`shipper_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `orders` VALUES (1,6,'2019-01-30',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (2,7,'2018-08-02',2,NULL,'2018-08-03',4);
INSERT INTO `orders` VALUES (3,8,'2017-12-01',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (4,2,'2017-01-22',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (5,5,'2017-08-25',2,'','2017-08-26',3);
INSERT INTO `orders` VALUES (6,10,'2018-11-18',1,'Aliquam erat volutpat. In congue.',NULL,NULL);
INSERT INTO `orders` VALUES (7,2,'2018-09-22',2,NULL,'2018-09-23',4);
INSERT INTO `orders` VALUES (8,5,'2018-06-08',1,'Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis.',NULL,NULL);
INSERT INTO `orders` VALUES (9,10,'2017-07-05',2,'Nulla mollis molestie lorem. Quisque ut erat.','2017-07-06',1);
INSERT INTO `orders` VALUES (10,6,'2018-04-22',2,NULL,'2018-04-23',2);


CREATE TABLE `order_items` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`order_id`,`product_id`),
  KEY `fk_order_items_products_idx` (`product_id`),
  CONSTRAINT `fk_order_items_orders` FOREIGN KEY (`order_id`) REFERENCES `orders` (`order_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_order_items_products` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_items` VALUES (1,4,4,3.74);
INSERT INTO `order_items` VALUES (2,1,2,9.10);
INSERT INTO `order_items` VALUES (2,4,4,1.66);
INSERT INTO `order_items` VALUES (2,6,2,2.94);
INSERT INTO `order_items` VALUES (3,3,10,9.12);
INSERT INTO `order_items` VALUES (4,3,7,6.99);
INSERT INTO `order_items` VALUES (4,10,7,6.40);
INSERT INTO `order_items` VALUES (5,2,3,9.89);
INSERT INTO `order_items` VALUES (6,1,4,8.65);
INSERT INTO `order_items` VALUES (6,2,4,3.28);
INSERT INTO `order_items` VALUES (6,3,4,7.46);
INSERT INTO `order_items` VALUES (6,5,1,3.45);
INSERT INTO `order_items` VALUES (7,3,7,9.17);
INSERT INTO `order_items` VALUES (8,5,2,6.94);
INSERT INTO `order_items` VALUES (8,8,2,8.59);
INSERT INTO `order_items` VALUES (9,6,5,7.28);
INSERT INTO `order_items` VALUES (10,1,10,6.01);
INSERT INTO `order_items` VALUES (10,9,9,4.28);

CREATE TABLE `sql_store`.`order_item_notes` (
  `note_id` INT NOT NULL,
  `order_Id` INT NOT NULL,
  `product_id` INT NOT NULL,
  `note` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`note_id`));

INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('1', '1', '2', 'first note');
INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('2', '1', '2', 'second note');


DROP DATABASE IF EXISTS `sql_hr`;
CREATE DATABASE `sql_hr`;
USE `sql_hr`;


CREATE TABLE `offices` (
  `office_id` int(11) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` varchar(50) NOT NULL,
  PRIMARY KEY (`office_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `offices` VALUES (1,'03 Reinke Trail','Cincinnati','OH');
INSERT INTO `offices` VALUES (2,'5507 Becker Terrace','New York City','NY');
INSERT INTO `offices` VALUES (3,'54 Northland Court','Richmond','VA');
INSERT INTO `offices` VALUES (4,'08 South Crossing','Cincinnati','OH');
INSERT INTO `offices` VALUES (5,'553 Maple Drive','Minneapolis','MN');
INSERT INTO `offices` VALUES (6,'23 North Plaza','Aurora','CO');
INSERT INTO `offices` VALUES (7,'9658 Wayridge Court','Boise','ID');
INSERT INTO `offices` VALUES (8,'9 Grayhawk Trail','New York City','NY');
INSERT INTO `offices` VALUES (9,'16862 Westend Hill','Knoxville','TN');
INSERT INTO `offices` VALUES (10,'4 Bluestem Parkway','Savannah','GA');



CREATE TABLE `employees` (
  `employee_id` int(11) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `job_title` varchar(50) NOT NULL,
  `salary` int(11) NOT NULL,
  `reports_to` int(11) DEFAULT NULL,
  `office_id` int(11) NOT NULL,
  PRIMARY KEY (`employee_id`),
  KEY `fk_employees_offices_idx` (`office_id`),
  KEY `fk_employees_employees_idx` (`reports_to`),
  CONSTRAINT `fk_employees_managers` FOREIGN KEY (`reports_to`) REFERENCES `employees` (`employee_id`),
  CONSTRAINT `fk_employees_offices` FOREIGN KEY (`office_id`) REFERENCES `offices` (`office_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `employees` VALUES (37270,'Yovonnda','Magrannell','Executive Secretary',63996,NULL,10);
INSERT INTO `employees` VALUES (33391,'D\'arcy','Nortunen','Account Executive',62871,37270,1);
INSERT INTO `employees` VALUES (37851,'Sayer','Matterson','Statistician III',98926,37270,1);
INSERT INTO `employees` VALUES (40448,'Mindy','Crissil','Staff Scientist',94860,37270,1);
INSERT INTO `employees` VALUES (56274,'Keriann','Alloisi','VP Marketing',110150,37270,1);
INSERT INTO `employees` VALUES (63196,'Alaster','Scutchin','Assistant Professor',32179,37270,2);
INSERT INTO `employees` VALUES (67009,'North','de Clerc','VP Product Management',114257,37270,2);
INSERT INTO `employees` VALUES (67370,'Elladine','Rising','Social Worker',96767,37270,2);
INSERT INTO `employees` VALUES (68249,'Nisse','Voysey','Financial Advisor',52832,37270,2);
INSERT INTO `employees` VALUES (72540,'Guthrey','Iacopetti','Office Assistant I',117690,37270,3);
INSERT INTO `employees` VALUES (72913,'Kass','Hefferan','Computer Systems Analyst IV',96401,37270,3);
INSERT INTO `employees` VALUES (75900,'Virge','Goodrum','Information Systems Manager',54578,37270,3);
INSERT INTO `employees` VALUES (76196,'Mirilla','Janowski','Cost Accountant',119241,37270,3);
INSERT INTO `employees` VALUES (80529,'Lynde','Aronson','Junior Executive',77182,37270,4);
INSERT INTO `employees` VALUES (80679,'Mildrid','Sokale','Geologist II',67987,37270,4);
INSERT INTO `employees` VALUES (84791,'Hazel','Tarbert','General Manager',93760,37270,4);
INSERT INTO `employees` VALUES (95213,'Cole','Kesterton','Pharmacist',86119,37270,4);
INSERT INTO `employees` VALUES (96513,'Theresa','Binney','Food Chemist',47354,37270,5);
INSERT INTO `employees` VALUES (98374,'Estrellita','Daleman','Staff Accountant IV',70187,37270,5);
INSERT INTO `employees` VALUES (115357,'Ivy','Fearey','Structural Engineer',92710,37270,5);


DROP DATABASE IF EXISTS `sql_inventory`;
CREATE DATABASE `sql_inventory`;
USE `sql_inventory`;


CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


select 
	wr.start_datetime,
	wr.end_datetime,
	wr.object_id,
	wr.reserved_by_user,
	wr.reserved_for_user,
	wr.reservation_hash,
	wo.object_name as objectName,
	wo.object_type as objectType
from wmt_reservations wr

left join wmt_objects wo 
	on wr.object_id = wo.object_id and wr.org = wo.org and wr.org_path = wo.org_path

left join wmt_reservation_guests wrg 
	on wrg.reservation_id = wr.id

where wr.org = 'okku' and wr.org_path = '/demo' and wr.cancelled_at is null and wr.visible_to_others is true
UNION all
select DISTINCT on
	(wo2.regular_user)
	wr2.start_datetime,
	wr2.end_datetime,
	wr2.object_id,
	wr2.reserved_by_user,
	wr2.reserved_for_user,
	wr2.reservation_hash,
	wo2.object_name as objectName,
	wo2.object_type as objectType
from wmt_objects wo2

left join wmt_reservations wr2
	on wr2.org = wo2.org and wr2.org_path = wo2.org_path 
where wo2.regular_user is not null
const redisClient = require('redis')
const logger = require('../services/Logger')

const ENV = process.env.ENV ? process.env.ENV : 'DEV'

class Redis {
    constructor() {
        this.client = redisClient.createClient({
            url: process.env.REDIS_URL
        })

        // create connection
        this.client.connect()
        logger.info(`Redis connection opened`)
        // get some connection diagnostics
        this.client
            .sendCommand(['CLIENT', 'LIST'])
            .then(list => {
                const clients = list.split('\n')
                logger.info(
                    `Redis client count: ${
                        clients.filter(x => x?.length > 0).length
                    }`
                )
            })
            .catch(err => logger.error(err))
    }

    /**
     * Stores key value pair in redis
     * @param {String} key
     * @param {String} value JSON stringified value
     */
    async put(key, value, ttl) {
        const options = {}
        if (ttl) {
            options.EX = ttl
        }
        await this.client.set(
            `${ENV}:${key}`,
            JSON.stringify(value),
            options
        )
    }

    /**
     * Get redis data by key
     * @param {String} key
     * @returns
     */
    async get(key) {
        // logger.info(`getting redis key: ${ENV}:${key}`)
        let data = await this.client.get(`${ENV}:${key}`)

        data = data ? JSON.parse(data) : undefined
        if (data && Object.keys(data).length === 0) data = undefined

        if (!data) {
            logger.info(`Redis cache miss on key ${ENV}:${key}`)
        }
        return data
    }

    /**
     * Remove cache entry
     * @param {String} key
     */
    async clear(key) {
        await this.client.del(`${ENV}:${key}`)
        logger.info(`Redis key: ${key} deleted`)
    }

    /**
     * Delete keys in wild card fashion
     * @param {String} pattern Example: h?llo, h*llo
     */
    async deleteKeysViaWildCardPattern(pattern) {
        logger.info(`Deleting redis keys for pattern: ${pattern}`)
        let cursorIndex = '0'
        let running = true
        do {
            const { cursor, keys } = await this.client.scan(
                cursorIndex,
                {
                    MATCH: `${ENV}:${pattern}`
                }
            )
            logger.info(`Deleting redis keys: ${keys}`)
            // Delete redis key
            keys.forEach(async key => {
                await this.client.del(`${key}`)
                logger.info(`Redis key: ${key} deleted`)
            })

            // update cursor
            cursorIndex = cursor

            // loop control variable
            if (!cursor) running = false
        } while (running)
    }

    /**
     * Set expiry time of the key in milliseconds
     * @param {*} key
     * @param {*} expiryTime
     */
    async setKeyExpireTime(key, expiryTime) {
        await this.client.expire(`${ENV}:${key}`, expiryTime)
    }

    async quit() {
        await this.client?.quit()
    }
}

module.exports = new Redis()
arr.reduce((pre, cur)=> [].concat.apply([], pre.map(t => cur.map(g => t + g))));
const file = bucket.file(`${folderName}/${fileName}`)
const passThroughStream = new stream.PassThrough()
passThroughStream.write(fileTitle)
passThroughStream.write(fileHeader)
passThroughStream.write(convertArrayToCSV(accounts.map(mapRecords)))
passThroughStream.end()

passThroughStream
  .pipe(file.createWriteStream())
  .on('error', (err) => {
  console.error(makeLogEntry(err))
})
  .on('finish', () => {
  console.log('writed')
})
$ npm install typescript --save-dev
$ npm install express
$ npm install --save-dev eslint @types/express @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier
$ npm install --save-dev ts-node-dev

// GENERATE TSCONFIG FILE FROM TERMINAL
$npm run tsc -- --init
$tsc --init

// PACKAGE.JSON
{
  // ..
  "scripts": {
    "start": "node dist/index.js",
    "build": "tsc --build",
    "clean": "tsc --build --clean",
    "tsc": "tsc",
    "dev": "ts-node-dev index.ts",
    "lint": "eslint src/**/*.ts",
     "format": "src/**/*.ts --fix",
  },
  // ..
}

// TSCONFIG.JSON
{
  "compilerOptions": {
    "target": "ES2018",
    "outDir": "dist",
    "sourceMap": true,
    "module": "commonjs",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "include": [
    "src/**/*.ts",
  ],
  "exclude": [
    "node_modules"
  ]
}

//.ESLINTRC
{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "plugins": [
    "@typescript-eslint"
  ],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "rules": {
    "indent": 0,
    "linebreak-style": 0,
    "quotes": [
      "error",
      "double"
    ]
  }
}
  
// PRETTIERRC
{
  "trailingComma": "all",
  "importOrder": [
    "<THIRD_PARTY_MODULES>",
    "next-seo.config",
    "^components/(.*)$",
    "^utils/(.*)$",
    "^assets/(.*)$",
    "^@fontsource/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}
 <Button component={Link} to='/auth' variant='contained'color='primary'>SignIn</Button>
require("dotenv").config();

const Discord = require("discord.js");

const Sequelize = require("sequelize");

const keep_alive = require("./keep_alive.js");

//const { MessageEmbed } = require('discord.js');

const token = process.env["DISCORD_BOT_SECRET"];

const prefix = "!";

​
require("dotenv").config();

const Discord = require("discord.js");

const Sequelize = require("sequelize");

const keep_alive = require("./keep_alive.js");

//const { MessageEmbed } = require('discord.js');

const token = process.env["DISCORD_BOT_SECRET"];

const prefix = "!";

​
 const {page}=req.query;
    console.log(page);
    try {
        const LIMIT=6; 
        // limit can be used dynamically
        const startIndex=(Number(page)-1 )* LIMIT;//getting the starting index of all the posts
        // converting page to Number because we get string as query

        const total=await PostMessage.countDocuments({});
        const posts = await PostMessage.find().sort({_id:-1}).limit(LIMIT).skip(startIndex); //skipping all the previous pages from loading
        
        res.status(200).json({data:posts,currentPage:Number(page),numberOfPages:Math.ceil(total/LIMIT)});
    }
    catch (error) {
        res.status(404).json({ message: error.message });

    }
/* 
Initialise node environment and install webpack as a dev dependency
$ npm init && npm install -D webpack webpack-cli webpack-dev-server

<dist> is the directory where built files are stored and <src/index.js> serves as the default entry file

In package.json "scripts", for the "build" script,
"scripts": {
	"build": "webpack",
	"dev": "webpack serve",
    "watch": "webpack --watch"
}


$ npm run build - to build
*/

/* 
Create a config file <webpack.config.js>. 
Install the HTML plugin as a dev dependency: $ npm i -D html-webpack-plugin
Install babel loader to maintain backwards compatibility with older browser versions: 
$ npm i -D babel-loader @babel/core @babel/preset-env
Install css loaders: $ npm i -D css-loader mini-css-extract-plugin
For sass: $ npm i -D sass-loader
*/

const path = require "path";
const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")

module.exports = {
  mode: "development", /* The environment. Other options include production */
  
  entry: {
    bundle: path.resolve(__dirname, "src/index.js"), /* The main file to be bundled */
  },
  
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name][contenthash].js", /* The created output file. By default <main.js>. The output file name depends on the property provided to "entry". Hence in this example, the output file will be called bundle.js. This file is served to the HTML file as a script. Adding the contentash will create a new output file after every build so */
    clean: true, /* Do not duplicate output files on each build. Maintain one file with changing hashes */
    assetModuleFilename: "[name][ext]" //Maitain filename after bundling
  },
  
  devtool: "source-map", /* Add source maps for debugging purposes */
  
  devServer: {
    static: {
      directory: path.resolve(__dirname, "dist"),
      port: 3000,
      open: true, //Open browser automatically on running $ npm run dev
      hot: true, //Hot reloading
      compress: true, //Enable gzip compression
      historyApiFallback: true,
    }
  },
  
  module: {
    rules: [
      /* The value of the test property refers to the file extension to be focused on, e.g. scsss, js, ts, etc. and the the value of the "use" property refers to the loaders needed to enable implementation of the specified files with the target extension */
      {
        test: /\s?.css$/i, //case insensitive
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"] //Read from LTR
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"]
          }
        }
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i, //case-insensitive
        type: "asset/resource"
      }
    ]
  },
  
  plugins: [
    new HtmlWebpackPlugin ({
    	title: "<Insert title of webapp>",
    	filename: "index.html",
      	template: "src/<insert template filename here>.html"
    }), /* Creates the HTML file with the necessary features based on the config. The template file serves as a boilerplate over which the plugin adds the other tags such as the title and script. The template is stored in the src directory */
    new MiniCssExtractPlugin()
  ]
  
}
//backend
//api

export const getPostsBySearch=async  (req,res)=>{
    const {searchQuery , tags}=req.query; 
    try {
       const title=new RegExp(searchQuery,'i');
       const posts=await PostMessage.find({$or:[{title},{tags:{$in:tags.split(',') }}]})
       //here we get tags as an array so finding the specific tag by spliting tags using array, because we get the array as an object here using ",". or = search by title or tags .RegExp = regex.

       res.json({data:posts})
    //    i for ignoring case 
    } catch (error) {
        
    }
}
//actions
 
export const getPostsBySearch=(searchQuery)=>async(dispatch)=>{
    try {
        
        const {data:{data}}=await api.fetchPostsBySearch(searchQuery);
        console.log(data);
    } catch (error) {
       console.log(error); 
    }
}
//action in front end

export const getPostsBySearch=(searchQuery)=>async(dispatch)=>{
    try {
        const {data:{data}}=await api.fetchPostsBySearch(searchQuery);
        console.log(data);
    } catch (error) {
       console.log(error); 
    }
}
///eta bahire\\\
function useQuery(){
    return new URLSearchParams(useLocation().search)
}
/// then vitore\\\
const query=useQuery();
    const page=query.get(page)
    /// page name e kono query thakle tar value dibe\\\
import jwt from 'jsonwebtoken'
const auth=async (req,res,next)=>{
    try {
       const token=req.headers.authorization.split(''[1]);
       const isCustomAuth=token.length<500;
       let decodedData;
       if(token && isCustomAuth){
               decodedData=jwt.verify(token,process.env.SECRET);
              req.userId=decodedData?.id;
       }
       else{
        decodedData=jwt.decode(token);
        req.userId=decodedData?.sub;
       }
       next();
    } catch (error) {
        console.log(error);
    }
}
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import user from '../models/user';

export const signin=async (res,req)=>{
 const {email,password} =req.body;
 try {
    const existingUser=await userfindOne({email: email});
    if(!existingUser) return res.status(404).json({message: 'user doesnot exist'});
    const isPasswordCorrect=await bcrypt.compare(password,existingUser.password);
    if(!isPasswordCorrect) return res.status(400).json({message: 'invalid credintials'});
    const token=jwt.sign({email:existingUser.email,id:existingUser._id},process.env.SECRET,{expiresIn:'1h'})
    res.status(200).json({result:existingUser,token})
 } catch (error) {
    res.status(500).json({message:'something went wrong'})
 }
}
export const signup=async (res,req)=>{

}
/* Install ts-node-dev as a dev dependency
Install eslint as dev dependency
Install TypeScript */

"scripts": {
    "tsc": "tsc",
    "dev": "ts-node-dev src/index.ts",
    "lint": "eslint --ext .ts",
    "start": "node build/index.js"
  }
import cors from "cors"; //ES6
const cors = require("cors"); //commonjs

const corsOptions = {origin: "*", methods: ["GET, HEAD, PUT, PATCH, POST, DELETE"], credentails: true, optionsSuccessStatus: 200};
app.use(cors(corsOptions));
$npm install --save-dev eslint @babel/eslint-parser eslint-plugin-react eslint-plugin-react-native ...

// AUTOMATIC CONFIG FILE
$npm init @eslint/config

//GLOBAL INSTALLATION AND USE
$npm i -g eslint
$eslint --init

// PACKAGE.JSON
{ //...,
  
  "devDependencies": {
    "@babel/eslint-parser": "^7.18.9",
    "@trivago/prettier-plugin-sort-imports": "^3.3.0",
    "@typescript-eslint/eslint-plugin": "^5.32.0",
    "@typescript-eslint/parser": "^5.32.0",
    "eslint": "^8.21.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.6.1",
    "eslint-plugin-react": "^7.30.1",
    "eslint-plugin-react-hooks": "^4.6.0"
  },
   //...
}

// TSCONFIG.JSON
{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src/**/*"
  ]
}


// .ESLINTRC
{
  "globals": {
    "module": true
  },
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "airbnb",
    "airbnb/hooks",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "@typescript-eslint"
  ],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": 0,
    "@typescript-eslint/explicit-module-boundary-types": 0,
    "react/react-in-jsx-scope": 0,
    "quotes": [
      "error",
      "double"
    ],
    "import/extensions": 0,
    "import/no-unresolved": 0,
    "linebreak-style": [
      "error",
      "windows"
    ],
    "operator-linebreak": "off",
    "react/jsx-filename-extension": 0,
    "no-shadow": "off",
    "jsx-a11y/label-has-associated-control": 0,
    "react/jsx-no-bind": 0,
    "no-unused-expressions": [
      "warn",
      {
        "allowShortCircuit": true,
        "allowTernary": true
      }
    ]
  }
}

// .PRETTIERRC
{
  "trailingComma": "all",
  "importOrder": [
    "^(next/(.*)$)|^(next$)",
    "<THIRD_PARTY_MODULES>",
    "next-seo.config",
    "^components/(.*)$",
    "^utils/(.*)$",
    "^assets/(.*)$",
    "^@fontsource/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
 if (typeId === 1) {
                // aca_book_list
                const deleteBook = await prisma.aca_book_list.update({
                    where: {
                        id: +productId,
                        // is_active: true,
                        // institution_id: +authData.institution_id,
                    },
                    data: {
                        is_active: false,
                    }
                })
                await BasicResponse(res, 1, 'Book Deleted', deleteBook)
                if (!deleteBook) {
                    await BasicResponse(res, 0, 'Book Not Found to Delete', [])
                    return
                }

            }

            if (typeId === 2 || typeId === 3) {
                // console.log(typeId, productId);
                let deleteProduct: any = await prisma.sm_products.findMany({
                    where: {
                        id: productId,
                        // is_active: true,

                    }
                    // data: {
                    //     is_active: false,
                    // },
                })
                console.log('deleteProduct ', deleteProduct)
                // if (!deleteProduct) {
                //     if (typeId === 2) {
                //         await BasicResponse(res, 0, 'A Copies Not Found to Delete', [])
                //         return
                //     }
                //     if (typeId === 3) {
                //         await BasicResponse(res, 0, 'A Stationery Not Found to Delete', [])
                //         return
                //     }
                // }

                // if (typeId === 2) {
                //     await BasicResponse(res, 1, 'A Copies Deleted', deleteProduct)
                // }
                // if (typeId === 3) {
                //     await BasicResponse(res, 1, 'A Stationery Deleted', deleteProduct)
                // }
            }
const fetch = require('node-fetch');

fetch("https://dink.ga/api/criarURL?url=SEU_URL").then(response => console.log(response)).catch(err => console.error(err));
const fs = require('fs');
const https = require('https');
const {Transform} = require('stream');

const transformGenerator = function() {
    let flushCallback = ()=>{};   
    const options = {
        host: <url>, //without protocol https://
        port: 443,
        path: </anything/after/slash>,
        method: 'POST' 
    };

    const transform = new Transform(); 
    const req = https.request(options, (res)=>{
        res.on('data', (d) => {
            transform.push(d);
        });

        res.on('end', () => {
            flushCallback();
            transform.destroy()
        });
    })

    transform._transform = (chunk, encoding, callback) => {
            req.write(chunk);
            callback()
    }

    transform.pipe(req);
    transform._flush = (cb)=>{
        req.end();
        flushCallback = cb;
    }
    return transform;
}

stream = fs.createReadStream('./example.txt');
stream.pipe(transformGenerator()).pipe(process.stdout);
const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./server-side/public/uploads");
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/jpeg" ||
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/gif"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5, // max 5mb
  },
  fileFilter: fileFilter,
});

module.exports = upload;
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  { timestamps: true }
);

module.exports = User = mongoose.model("User", userSchema);


// @routes  GET api/user/stats
// @desc    Get how many users are registered with in a year/month/week
// @access  Private - Admin
router.get("/stats", isAuthenticatedAndAdmin, async (req, res) => {
  User.aggregate([
    // { $match: { createdAt: { $gte: currentYear } } },
    {
      $project: {
        year: { $year: "$createdAt" },
        month: { $month: "$createdAt" },
        week: { $week: "$createdAt" },
      },
    },
    {
      $group: {
        _id: { year: "$year", month: "$month", week: "$week" },
        count: { $sum: 1 },
      },
    },
  ])
    .then((userStats) => res.status(200).json(userStats))
    .catch((err) => res.status(500).json(err));
});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const orderSchema = new Schema(
  {
    userId: {
      type: ObjectId,
      ref: "User",
    },
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    size: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      required: true,
    },
    quantity: {
      type: Number,
      default: 1,
    },
    totalPrice: {
      type: Number,
      required: true,
    },
    paymentMethod: {
      type: String,
      default: "Stripe",
    },
  },
  { timestamps: true }
);

module.exports = Order = mongoose.model("Order", orderSchema);


// @routes  GET api/order/income
// @desc    Get monthly income
// @access  Private - Admin
router.get("/income", isAuthenticatedAndAdmin, (req, res) => {
  const date = new Date();
  const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
  const previousMonth = new Date(date.setMonth(lastMonth.getMonth() - 1));

  Order.aggregate([
    { $match: { createdAt: { $gte: previousMonth } } },
    { $project: { month: { $month: "$createdAt" }, sales: "$amount" } },
    { $group: { _id: "$month", total: { $sum: "$sales" } } },
  ])
    .then((income) => res.status(200).json(income))
    .catch((err) => res.status(500).json(err));
});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const reviewSchema = new Schema(
  {
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    reviews: [
      {
        userId: {
          type: ObjectId,
          ref: "User",
        },
        rating: {
          type: Number,
          required: true,
        },
        comment: {
          type: String,
        },
      },
    ],
    totalRate: {
      type: Number,
      default: 0,
    },
  },
  { timestamps: true }
);

router.get("/:id", (req, res) => {
  Review.findOne({ productId: req.params.id })
    .populate({
      path: "reviews",
      populate: { path: "userId", select: "-_id username" },
    })        
    .then((reviews) => {      
        res.status(200).json(reviews);      
    })
    .catch((err) => res.status(500).json(err));
});
const request = require('supertest');
const assert = require('assert');

request('https://dog.ceo')
  .get('/api/breeds/image/random')
  .expect(200) // assert HTTP status code
  .expect('Content-Type', 'application/json') // assert content type
  .expect(function(res) { // assert body JSON structure
    assert(res.body.hasOwnProperty('status'));
    assert(res.body.hasOwnProperty('message'));
  })
  .end(function(err, res) {
    if (err) throw err;
  });
import { realpathSync as realpath, accessSync as access, existsSync as exists } from 'fs'
import { dirname } from 'path'

/**
 * IIFE to resolve Magento document root
 * @returns <string> Returns Magento document root
 */
export const mageRoot = (() => {
    let mageRoot = dirname(realpath(import.meta.url.slice(7)))

    while (!(exists(`${ mageRoot }/app/Mage.php`) || exists(`${ mageRoot }/bin/magento`))) {
        mageRoot = dirname(mageRoot)
    }

    return mageRoot
})()
FROM node:10.23.0-alpine3.10

RUN apk update && \
mkdir -p /app && chmod 0775 /app && \
rm -rf /var/lib/apt/lists/

#install nodemon 
RUN npm install -g nodemon --unsafe-perm=true --allow-root

#Aggiunta degli applicativi
RUN apk --no-cache add redis dcron procps

COPY entrypoint-dev.sh /entrypoint.sh

CMD ["/entrypoint.sh"]
res.status(404).render('your_template', your_data );
  const filteredData = datas[0].PostOffice.map(({ Name, State }) => {
    return { Name, State };
  });
 process.on('unhandledRejection', (error) => {
    throw error;
  });

  process.on('uncaughtException', (error) => {
    logError(error);

    if (!isOperationalError(error)) {
      process.exit(1);
    }
  });
db.customers.find({}).forEach(function (ch){db.customers.updateMany({},{$set:{"contact":ch.contact.toString()}})});
//Host Dosyası
sudo nano /etc/hosts 
Control+O
Control+X
Node Port Kill
lsof -i :3000
kill -9 PID
// From postman:
{
    "select": {"productName": "Skykick"}
}

// In file:
    req.body.select,
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
// require mongoose
const mongoose = require('mongoose');
// require config file to access mongoURI 
const config = require('config');
// make our db the mongoURI
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
       await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })
        console.log('mongo db connected')
    } catch (err) {
        console.error(err)
        //exit with failure
        process.exit(1)
    }
}

module.exports = connectDB;
//To see all versions of Node that are installed on your machine use the command:
$ npm -v

//To see versions installed on machine

$ nvm ls
->      v16.1.0
         system
default -> node (-> v16.1.0)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v16.1.0) (default)
stable -> 16.1 (-> v16.1.0) (default)

// add a new version
$ nvm install <version>
  
// to switch to a different verison
  
$ nvm use <version>
const getSourcesData = asyncHandler(async (req, res) => {
  const { dealership } = req.user;
  const month = parseInt(req.params.month);
  const customerData = await Customer.aggregate()
    .match({ dealership })
    .facet({
      fbCount: [
        {
          $match: {
            sourceOfEnquiry: "Facebook",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "fbCount" },
      ],
      googleCount: [
        {
          $match: {
            sourceOfEnquiry: "Google",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },

        { $count: "googleCount" },
      ],
      cardekhoCount: [
        {
          $match: {
            sourceOfEnquiry: "Cardekho",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "cardekhoCount" },
      ],
      carwaleCount: [
        {
          $match: {
            sourceOfEnquiry: "Carwale",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "carwaleCount" },
      ],
      instagramCount: [
        {
          $match: {
            sourceOfEnquiry: "Instagram",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "instagramCount" },
      ],
      newspaperAdsCount: [
        {
          $match: {
            sourceOfEnquiry: "Newspaper Ads",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "newspaperAdsCount" },
      ],
      websiteCount: [
        {
          $match: {
            sourceOfEnquiry: "Website",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "websiteCount" },
      ],
      hoardingsCount: [
        {
          $match: {
            sourceOfEnquiry: "Hoardings",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "hoardingsCount" },
      ],
      telephonicCount: [
        {
          $match: {
            sourceOfEnquiry: "Telephonic",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "telephonicCount" },
      ],
      referralCount: [
        {
          $match: {
            sourceOfEnquiry: "Referral",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "referralCount" },
      ],
      workshopCount: [
        {
          $match: {
            sourceOfEnquiry: "Workshop",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "workshopCount" },
      ],
      bushfireCount: [
        {
          $match: {
            sourceOfEnquiry: "Bushfire",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "bushfireCount" },
      ],
      managementCount: [
        {
          $match: {
            sourceOfEnquiry: "Management",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "managementCount" },
      ],
      walkInCount: [
        {
          $match: {
            sourceOfEnquiry: "Walk-in",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "walkInCount" },
      ],
    });
  

  return res.status(200).json({
    success: true,
    tableData: customerData,
  });
});
{
  sourceOfEnquiry:'Telephonic',
    createdAt: {
        $gte: ISODate("2021-06-01T00:00:00.000Z"),
        $lte: ISODate("2021-06-30T00:00:00.000Z")
    }
}
db.users.updateMany(
  { __t: "SE" },
  {
    $set: {
      targets: [
        {
          modelName: "rapid",
          targetCount: 15,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "superb",
          targetCount: 10,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "kushaq",
          targetCount: 5,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "octavia",
          targetCount: 0,
          bookingCount: 0,
          deliveredCount: 0,
        },
      ],
    },
  }
);
//create a file test.rest:
GET http://localhost:5000
# Push the commit and update the deployed version on Heroku
git push heroku main

# Open the app in the browser (from terminal)
heroku open

#fetch heroku logs
heroku logs

#specify number of logs
heroku logs -n 200

#find all your fucking heroku deployment errors then cry yourself to sleep
heroku logs --tail

# Open the terminal in the app dyno in Heroku
heroku run bash
 
# Run a file 
node seeds/index.js
# Open the terminal in the app dyno in Heroku

heroku run bash

 

# We may then run the seed file

node bin/seed.js
const dateFilter = asyncHandler(async (req, res) => {
  const month = 7;
  const day = 13;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $and: [
            { $eq: [{ $month: "$birthday" }, month] },
            { $eq: [{ $dayOfMonth: "$birthday" }, day] },
          ],
        },
        {
          $and: [
            { $eq: [{ $month: "$anniversary" }, month] },
            { $eq: [{ $dayOfMonth: "$anniversary" }, day] },
          ],
        },
      ],
    },
  });
  res.send(feedbacks);
});
const dateFilter = asyncHandler(async (req, res) => {
  const month = 6;
  const day = 10;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $eq: [{ $month: "$birthday" }, month],
          $eq: [{ $dayOfMonth: "$birthday" }, day],
        },
        {
          $eq: [{ $month: "$anniversary" }, month],
          $eq: [{ $dayOfMonth: "$anniversary" }, day],
        },
      ],
    },
  });
  console.log({ feedbacks });
});
hbs.registerHelper(`iff`, function (a, operator, b, opts) {
    let bool = false;
    a.toString();
    b.toString();
    switch (operator) {
        case `===`:
            bool = a === b;
            break;
        case `>`:
            bool = a > b;
            break;
        case `<`:
            bool = a < b;
            break;
        default:
            bool = a === b;
    }

    if (bool) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

{{#iff value1 '>' value2}}
do the thing
{{/iff}}
//cons name = 'me'

{{log 'author = ' name }}

//author = me
// in app.js
hbs.registerHelper(`ifEquals`, function (a, b, opts) {
    if (a.toString() === b.toString()) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

// in hbs template
{{#ifEquals name 'Foo'}}
      true
{{else}}
      false
{{/ifEquals}}
const comparePassword = async (password, hash) => {
    try {
        // Compare password
        return await bcrypt.compare(password, hash);
    } catch (error) {
        console.log(error);
    }

    // Return false if error
    return false;
};

//use case
(async () => {
    // Hash fetched from DB
    const hash = `$2b$10$5ysgXZUJi7MkJWhEhFcZTObGe18G1G.0rnXkewEtXq6ebVx1qpjYW`;

    // Check if password is correct
    const isValidPass = await comparePassword('123456', hash);

    // Print validation status
    console.log(`Password is ${!isValidPass ? 'not' : ''} valid!`);
    // => Password is valid!
})();
const mongoose = require('mongoose');

const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test';          // REPLACE WITH YOUR OWN DB NAME

const connectDB = async () => {
    try {
        await mongoose.connect(`mongodb://${server}/${database}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true
        });

        console.log('MongoDB connected!!');
    } catch (err) {
        console.log('Failed to connect to MongoDB', err);
    }
};

connectDB();
function promiseWrapper(fn) {
    return (req, res, next) => {
         fn(req, res).catch(next);
    };
}
Using Git and Heroku

1) In terminal - git init

This creates a hidden file .git

2) git add .

This will creating a new copy of the work. This is a staging area.

3) git commit -m "Initial Commit"

This will making a commit of the version

[ These stages can be done using GitHub Desktop]

4) Then on terminal: heroku login

This will offers to open a browser. On the window that opened log in and close the window. 

5) $ heroku git:remote -a <name> if already created on heroku - or -   heroku create

this will show something like this in terminal:

https://still-gorge-92777.herokuapp.com/ | https://git.heroku.com/still-gorge-92777.git

6) Create Procfile

$ touch Procfile 

7) Find Procfile (should be empty) and add: web: node app.js (same file as we use for starting the application with nodemon).

8) Need to change port address to heroku’s dynamic port:

let port = process.env.PORT;if (port == null || port == "") { port = 3000;};app.listen(port, function () { console.log("Server started successfully");});

9) Choose a database host - we already have that so ignore.

10) Language specific setup: 

Need to specify the version of node to heroku:

in terminal: $ node --version, 

then in package.json add: 

"engines": { "node": "12.x" } [or whatever version. No need to be totally specific hence the ‘x’]. Can insert before the dependencies start.

11) Create .gitingnore file:

touch .gitignore and in .gitignore: 

/node_modules

npm-debug.log.

DS_Store

/*.env

12) Deploy on heroku: 

Before deploying - push to git one more time for last changes to be added:

git add . 

git commit -m “<chanages made to go in here>”

$ git push heroku master

[note: at this point I had an error message: ‘error: src refspec master does not match any’.

I needed to change the branch from ‘main’ on the bottom left of vs code to ‘master’ by adding a branch master through vs code. I then pushed again and it worked.]

Committing directly to git:

https://stackoverflow.com/questions/46877667/how-to-add-a-new-project-to-github-using-vs-code - below is the relevant content:

1) Navigate to the local project directory and create a local git repository: (already done above)

 git init


2) Once that is successful, click on the 'Source Control' icon on the left navbar in VS-Code.One should be able to see files ready to be commit-ed. Press on 'Commit' button, provide comments, stage the changes and commit the files. Alternatively you can run from CLI (already done abovre)

git commit -m "Your comment"


3) Now you need to visit your GitHub account and create a new Repository. Exclude creating 'README.md', '.gitIgnore' files. Also do not add any License to the repo. Sometimes these settings cause issue while pushing in.

4) Copy the link to this newly created GitHub Repository.

5) Come back to the terminal in VS-CODE and type these commands in succession:

git remote add origin <Link to GitHub Repo>     //maps the remote repo link to local git repo

git remote -v                                  //this is to verify the link to the remote repo 

git push -u origin master // or main                      // pushes the commit-ed changes into the remote repo

 6) You can see the success message in the Terminal. You can also verify by refreshing the GitHub repo online.

Once done can change branch used from master to main: 

To switch the default branch used to deploy apps from master to main, first create a new branch locally:

git checkout -b main


Next, delete the old default branch locally:

git branch -D master


From there, the local environment only knows about the main branch.

Reset the GIT repository hosted on the Heroku Platform using the heroku-reset command from the heroku-repo CLI plugin. Doing so will not impact the running application. (Note: Please communicate this change with your team. If you are working with other developers who are not aware of the reset, they might push to "master" which will overwrite the reset).

Re-deploy the application using the new default branch:

git push heroku main

To push directly to github: 

The git push command takes two arguments:

A remote name, for example, origin

A branch name, for example, main

For example:

git push  <REMOTENAME> <BRANCHNAME> 

app.get('/downloadFile', function (req, res) {
  var file = path.join(__dirname, '/pdfs/');
  res.download(file, function (err) {
    if (err) {
      console.log('Error');
      console.log(err);
    } else {
      console.log('Success');
    }
  });
});
test('should verify typed', async () => {
  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 10,
    args: ['--window-size=1920,1080']
  })
  const page = await browser.newPage()
  await page.goto(url)
  await page.type('.input-text', 'Hello World!')

  const finalText = await page.$eval('input.input-text', el => el.textContent)
  expect(finalText).toBe(finalText)
})
const bookingNumber = `${_.upperCase(modelName)}${_.random(1000000, 9999999)}
const {getIntroduction} = require('./util')

test('should output name and age', () => {
  const text = getIntroduction('Max', 20)
  expect(text).toBe('Max is 20 years old')
})
"scripts": {
  "test": "jest",
   "start": "node index.js"
},
"devDependencies": {
  "jest": "^26.6.3"
}
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
const updateStatus = asyncHandler(async (req, res) => {
  console.log("k");
  const { customer, stageFiveId, availableLoansId, status } = req.body;
  console.log(req.body);
  const customerData = await Customer.updateMany(
    {
      _id: customer,
    },
    // db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
    {
      $set: { "stage5.$[i].availableLoans.$[j].status": status },
    },
    { arrayFilters: [{ "i._id": stageFiveId }, { "j._id": availableLoansId }] }
  );
  console.log(customerData);
  if (customerData)
    return res.status(200).json({
      success: true,
      message: "Status updated sucessfully!",
    });
  else
    return res.status(400).json({
      success: false,
      message: "Could not able to update Status!",
    });
});
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({},
  [{ $set : { n : {$arrayElemAt:[{ $split: ["$customerName", " "] },1]}} }],

);
db.customers.updateMany({},
  [{ $set : { m : {$arrayElemAt:[{ $split: ["$customerName", " "] },0]}} }],

);
const fetch = require('isomorphic-fetch')


const query = fetch('https://www.freecodecamp.org/page-data/sq/d/4195245674.json')
    .then(resp => resp.json())
    .then(data => {
        // console.log(data)
        return data.data.allChallengeNode.edges.map(e => {
            // console.log(e.node)
            const url_pieces = e.node.fields.slug.split('/')
            return { 
                name: e.node.title, 
                cert: url_pieces[2], 
                section: url_pieces[3], 
                task: url_pieces[4] 
            }
        })
    }).then(q => console.log(q))
await new Promise(r => setTimeout(r, 5000));
const getModels = asyncHandler(async (req, res) => {
  const { modelName } = req.query;
  const dealership = await Dealership.aggregate([
    { $match: { _id: req.user.dealership } },
    {
      $project: {
        models: {
          $filter: {
            input: "$models",
            as: "models",
            cond: {
              $regexMatch: {
                input: "$$models.modelName",
                regex: `^${modelName}`,
                options: "i",
              },
            },
          },
        },
      },
    },
  ]);
  const models = dealership[0].models;
  return res.status(200).json({
    success: true,
    quesData: models,
  });
});
npx gsx-pdf-optimize raw_pdf.pdf optimized_pdf.pdf --dpi=150
// Script-wide timeout for wait and waitAndFind functions (in ms)
var startTime = new Date(),
  thisStep = 0,
  assert = require('assert'),
  Q = require('q'),
  ScriptTimeout = 0,
  MaintenanceMessage = "Script is running during maintenance window";

var log = function(msg) {
  if(typeof msg === "string")
  {
    var totalTimeElapsed = (new Date() - startTime);
    var elapsedSecs =  totalTimeElapsed / 1000;
    console.log('Step ' + thisStep + ': ' + elapsedSecs.toFixed(2) + 's: ' + msg);
    thisStep++;
    
    if(ScriptTimeout > 0 && totalTimeElapsed > ScriptTimeout)
    {
      throw Error('Script timed out. ' + totalTimeElapsed + 'ms is longer than script timeout threshold of ' + ScriptTimeout + 'ms.'); 
    }
  }
};

log("Initialising ...");

 // checks if this run is in within the maintenance window provided
 // @param {string} dayOfWeek - Monday, Tuesday, etc.
 // @param {string} startTime - UTC start time of window in 24hr format
 // @param {string} endTime - UTC end time of window in 24hr format
var checkInMaintenanceWindow = function(dayOfWeek, startTime, endTime)
{
  log("checkInMaintenanceWindow");
  var deferred = Q.defer();
  var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var now = new Date();
  var day = daysOfWeek[now.getUTCDay()];
  
  if(day != dayOfWeek)
  {
    log("Days do not match");
    deferred.resolve("Days do not match"); // not the specified day
  }
  else
  {
    log("Days match, checking times");
    startParts = startTime.split(":");
    var start = new Date(now);
    start.setUTCHours(parseInt(startParts[0]), parseInt(startParts[1]));

    endParts = endTime.split(":");
    var end = new Date(now);
    end.setUTCHours(parseInt(endParts[0]), parseInt(endParts[1]));

    // check if we are in the maintenance window
    if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime())
    {
      log("In maintenance window");
      $http.get("http://www.google.co.uk"); // workaround for monitor produced no traffic error
      deferred.reject(MaintenanceMessage);
    }
    else
    {
      deferred.resolve("Times do not match");
    }
  }  
  return deferred.promise;
};

function shouldDisplayError(message)
{
  return !(typeof message != "undefined" && message !== null && message.length > 0);
}

var buildSecurityOptions = function()
{
  var deferred = Q.defer();
  log("Building security options");
  // build your security options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "https://login.salesforce.com/services/oauth2/token",
    //Define body of POST request.
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    form: {
      grant_type: 'password',
      client_id: 'client ID',
      client_secret: 'Client Secret',
      username: 'username',
      password: 'password'
    }
  };
  
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var getSecurityToken = function(options){
  var deferred = Q.defer();
  log("Retrieving Security Token");
  $http.post(options, function(error, response, body)
  {
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }    
  });
  return deferred.promise; //promise is returned
};

var extractSecurityToken = function(data){
  log("Extracting Security Token");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(data);
  log("Security token retrieved successfully");
  deferred.resolve(info.access_token);
  return deferred.promise;
};

var buildApiOptions = function(securityToken){
  var deferred = Q.defer();
  log("Building API options");
  // build your api options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "http://url.com",
    //Define body of PATCH request.
    headers: {'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + securityToken},
    body: {
      "Description": "fooba3r"
    },
    json: true

  };
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var makeApiCall = function(options){
  var deferred = Q.defer();
  log("Making API call");

  //Make PATCH request, passing in options and callback.
  $http.patch(options, function(error, response, body){
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 204 (No Content) response code.
      assert.ok(response.statusCode == 204, 'Expected 204 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }
  });
  return deferred.promise; //promise is returned
};

var validateApiCall = function(body){
  log("Validating Api Call");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  //var info = JSON.parse(body);
  //assert.ok(shouldDisplayError(info.ErrorMessage), "Error Message: " + info.ErrorMessage);
	
  // perform any other validation here
  log("Completed successfully");
  deferred.resolve();
  return deferred.promise;
};

checkInMaintenanceWindow("Friday", "00:00", "01:30")
.then(function(){
  return buildSecurityOptions()
  .then(getSecurityToken)
  .then(extractSecurityToken)
  .then(buildApiOptions)
  .then(makeApiCall)
  .then(validateApiCall);
},
function(message){
  if(message != MaintenanceMessage)
  {
    throw new Error(MaintenanceMessage);
  }
  else
  {
    log(message);
  }
})
.done();
//Import the `assert` module to validate results.
var assert = require('assert');

var options = {
    url: "https://some_url.com",
        "headers": {
          "oauth_clientid": 123,
          
          },
        //"timeout": 15000
        };

$http.get(options, function(error, response, body) {
    console.log(response.statusCode + " status code")
    assert.ok(response.statusCode == 401, 'Expected 401 OK response');  
      });
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout});

var program = function(){
    rl.question("type question", function(answer) {
        switch (answer){
            case "option 1":
                //action 1;
                break;
            case "exit option":
            	//previous action
            	return rl.close();
            default:
                //default action
        }
        program();
    });
}

program();
app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:
//get method for retrieving data.
app.get('/', function (req, res) {
  res.send('Hello World!')
})
 Save
Respond to POST request on the root route (/), the application’s home page:
//send method for sending data.
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
 Save
Respond to a PUT request to the /user route:
//put request to 
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
 Save
Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})
Basic routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
 Save
Where:

app is an instance of express.
METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
function processSQLFile(fileName) {

  // Extract SQL queries from files. Assumes no ';' in the fileNames
  var queries = fs.readFileSync(fileName).toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' ') // excess white space
    .split(";") // split into all statements
    .map(Function.prototype.call, String.prototype.trim)
    .filter(function(el) {return el.length != 0}); // remove any empty ones

  // Execute each SQL query sequentially
  queries.forEach(function(query) {
    batch.push(function(done) {
      if (query.indexOf("COPY") === 0) { // COPY - needs special treatment
        var regexp = /COPY\ (.*)\ FROM\ (.*)\ DELIMITERS/gmi;
        var matches = regexp.exec(query);
        var table = matches[1];
        var fileName = matches[2];
        var copyString = "COPY " + table + " FROM STDIN DELIMITERS ',' CSV HEADER";
        var stream = client.copyFrom(copyString);
        stream.on('close', function () {
          done();
        });
        var csvFile = __dirname + '/' + fileName;
        var str = fs.readFileSync(csvFile);
        stream.write(str);
        stream.end();
      } else { // Other queries don't need special treatment
        client.query(query, function(result) {
          done();
        });
      }
    });
  });
}
command line

npm init -y (creates the package for dependencies)

npm i [module]  (creates dependency key and module repository)
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      // "processId": "${command:PickProcess}",
      "protocol": "inspector",
      "restart": true,
      "name": "Launch Programa",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
$ sudo npm install --global cross-env
var express = require('express');
var app = express();

app.enable('trust proxy'); //to detect if req.secure is true/false

//Block http requests. Only allow https requests
app.use(function (req, res, next) {
	if (req.headers['x-forwarded-proto'] !== 'https'){
      return res.status(404).send('Not found');
    } else {
    next();
    }
})

exports = module.exports = app;
router.get("/search/:page", (req, res, next) => {
  const resultsPerPage = 5;
  const page = req.params.page >= 1 ? req.params.page : 1;
  const query = req.query.search;

  Product.find({ name: query })
    .select("name")
    .sort({ name: "asc" })
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((results) => {
      return res.status(200).send(results);
    })
    .catch((err) => {
      return res.status(500).send(err);
    });
});
userSchema.pre('save', async function(next){
    if (!this.isModified('password')) return next()
    this.password = await bcrypt.hash(this.password, 8)

    next()
})
//You must require fs and path before this action can be done
//set this on the top of the model
const imagePath = 'uploads/image'


//Create a virtual with the schema name e.g.
blogSchema.virual('imagePath').get(function(){
if(this.image != null){
return path.join('/', imagePath, this.image)
}
})

//exports the imagePath as like this
module.exports.imagePath = imagePath 


//go to the route and require it with the model name e.g.
const uploadPath = path.join("public", BlogModel.imagePath);

//set your function for unlink and call it on the delete route
function removeImage(image){
	fs.unlink(uploadPath, image), (err)=>{
    if(err) console.log(err)
    })
}

// Let generalize user data
app.use((req, res, next) => {
    res.locals.user = req.isAuthenticated() ? req.user : null
    return next()
})
const passport = require('passport')
const LocalStrategy = require("passport-local").Strategy;

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
const flashMsg = (req, res, next) => {
    if (req.session.flashData) {
        for (const key in req.session.flashData) {
            res.locals[key] = req.session.flashData[key]
        }

        req.session.flashData = null
    }
     
    next()
}

module.exports = flashMsg
const mongooseValidation = (theError) => {
    const errors = {}
    const details = errors.theError
    for (const key in details)
    {
        errors[key] = [details[key].message]
    }
    return errors
}

module.exports = mongooseValidation
var {src, dest, watch}        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Static server
  function bs() {
    serveSass();
  browserSync.init({
      server: {
          baseDir: "./"
      }
  });
  watch("./*.html").on('change', browserSync.reload);
  watch("./scss/**/*.scss", serveSass);
  watch("./js/*.js").on('change', browserSync.reload);
};

// Compile sass into CSS & auto-inject into browsers
 function serveSass() {
  return src("./scss/*.scss")
      .pipe(sass())
      .pipe(dest("./css"))
      .pipe(browserSync.stream());
};

exports.serve = bs;
var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
var stripe = require('stripe')('sk_test_LIPsyf7cwBv0pbWPbzjeqAhj009wgDByN7');

stripe.customers.create(
  {
    description: 'My First Test Customer (created for API docs)',
  },
  function(err, customer) {
    // asynchronously called
  }
);
var express = require("express");
var app = express();
const session = require('express-session');
var MemcachedStore = require('connect-memjs')(session);

// configure sessions
var store = new MemcachedStore({servers: [process.env.MEMCACHEDCLOUD_SERVERS], username: process.env.MEMCACHEDCLOUD_USERNAME, password: process.env.MEMCACHEDCLOUD_PASSWORD});
app.use(session({ secret: 'keyboard cat',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true }, 
   store: store
}))
                                exports.removeById = (req, res) => {
   UserModel.removeById(req.params.userId)
       .then((result)=>{
           res.status(204).send({});
       });
};

                                
                                var app = express()
var sess = {
  secret: 'keyboard cat',
  cookie: {}
}
 
if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}
 
app.use(session(sess))
                                
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function (result) {
       alert("The result is "+result);
	}
});
                                
<form action="/new" method="post">

  <input name="title" type="text">
  <input name="description" type="text">
  <input name="steps[0][text]" type="text">
  <input name="steps[0][ingredients]" type="text">
  <input name="steps[1][text]" type="text">
  <input name="steps[1][ingredients]" type="text">
  <button type="submit">Submit Form</button>

</form>
const songs[];
const results;

for (var i, i++, i<songs.length){
    if(song[i].artist == "Drake"){
      result.push(songs[i]);
    };

// OR

const songs [];
const result = songs.filter ( song => song.artist == "Drake");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var slug = require('mongoose-slug-generator');

mongoose.plugin(slug);

const pageSchema = new Schema({
    title: { type: String , required: true},
    slug: { type: String, slug: "title" }
});

var Page = mongoose.model('Page', pageSchema);
module.exports = Page;
router.post('/:id/edit', auth.requireLogin, (req, res, next) => {
  Post.findByIdAndUpdate(req.params.id, req.body, function(err, post) {
    if(err) { console.error(err) };

     res.redirect(`/`+req.params.id);
  });
});
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
star

Tue Oct 04 2022 11:32:44 GMT+0000 (UTC) https://kuchbhilearning.blogspot.com/2022/09/attaching-lambda-secret-manager.html

#aws #aws-cdk #secret-manager #lambda #nodejs
star

Tue Oct 04 2022 11:26:02 GMT+0000 (UTC) https://kuchbhilearning.blogspot.com/2022/09/api-gateway-custom-domain-using-aws-cdk.html

#apigateway #aws-cdk #aws #lambda #route53 #nodejs #restapi
star

Fri Sep 23 2022 14:16:27 GMT+0000 (UTC)

#javascript #nodejs #typescript
star

Fri Sep 23 2022 14:15:03 GMT+0000 (UTC)

#javascript #nodejs #typescript
star

Thu Sep 15 2022 16:14:27 GMT+0000 (UTC)

#javascript #nodejs
star

Thu Sep 15 2022 05:44:35 GMT+0000 (UTC) https://www.hivelance.com/binance-clone-script

#javascript #php #nodejs #laravel
star

Wed Sep 07 2022 16:45:41 GMT+0000 (UTC)

#javascript #nodejs
star

Mon Sep 05 2022 13:32:00 GMT+0000 (UTC)

#javascript #nodejs
star

Wed Aug 24 2022 04:59:02 GMT+0000 (UTC) https://search.brave.com/search?q

#nodejs #react.js
star

Wed Aug 10 2022 09:47:51 GMT+0000 (UTC)

#javascript #nodejs
star

Wed Aug 10 2022 09:45:44 GMT+0000 (UTC)

#javascript #nodejs
star

Thu Jul 28 2022 22:53:13 GMT+0000 (UTC) https://fullstackopen.com/en/part9/typing_the_express_app

#javascript #nodejs #typescript
star

Tue Jul 19 2022 09:36:21 GMT+0000 (UTC) https://srcshare.io/?id

#nodejs
star

Tue Jul 19 2022 09:34:59 GMT+0000 (UTC) https://srcshare.io/?id

#nodejs
star

Mon Jul 18 2022 20:50:42 GMT+0000 (UTC)

#javascript #nodejs #jwt #login
star

Mon Jul 18 2022 19:58:59 GMT+0000 (UTC)

#nodejs
star

Sat Jul 16 2022 20:23:03 GMT+0000 (UTC) https://www.youtube.com/watch?v=VsUzmlZfYNg&t=12191s

#javascript #nodejs #jwt #login
star

Sun Jul 10 2022 08:36:11 GMT+0000 (UTC)

#javascript #nodejs
star

Sun Jul 10 2022 08:19:18 GMT+0000 (UTC) https://eslint.org/docs/latest/user-guide/getting-started

#javascript #nodejs #react.js
star

Sat Jul 09 2022 19:49:44 GMT+0000 (UTC) https://affiliate.traforce.com/v2/statistics/countries?date_from

#nodejs
star

Wed Jun 29 2022 08:34:13 GMT+0000 (UTC) https://github.com/nvm-sh/nvm

#nodejs
star

Mon Jun 06 2022 07:24:48 GMT+0000 (UTC)

#nodejs #prisma
star

Sun Jun 05 2022 14:47:22 GMT+0000 (UTC)

#nodejs
star

Tue May 31 2022 16:49:23 GMT+0000 (UTC)

#nodejs
star

Tue Apr 19 2022 04:56:54 GMT+0000 (UTC) https://github.com/jmerle/node-icecream

#nodejs
star

Thu Apr 07 2022 14:59:13 GMT+0000 (UTC)

#nodejs
star

Fri Mar 25 2022 08:01:16 GMT+0000 (UTC) https://reactgo.com/nvm-set-default-node-version/

#nodejs
star

Sun Mar 20 2022 11:24:15 GMT+0000 (UTC)

#mongo #nodejs
star

Sat Jan 08 2022 06:00:50 GMT+0000 (UTC) https://gist.github.com/juliyvchirkov/2c5c8d54b182528e39d4565d1632f8ee#file-magentodocumentroot-mjs

#javascript #nodejs #magento #document_root #resolve #module #mjs
star

Wed Nov 17 2021 13:19:30 GMT+0000 (UTC)

#nodejs #redis #nodemon
star

Wed Nov 17 2021 13:16:18 GMT+0000 (UTC)

#nodejs
star

Tue Aug 24 2021 16:30:12 GMT+0000 (UTC) https://sematext.com/blog/node-js-error-handling/

#nodejs #promises #unhandled
star

Sat Aug 14 2021 22:15:34 GMT+0000 (UTC)

#nodejs
star

Sat Aug 14 2021 22:15:00 GMT+0000 (UTC)

#nodejs
star

Thu Jul 15 2021 09:01:12 GMT+0000 (UTC)

#mongodb #mongoose #nodejs
star

Mon Jul 05 2021 11:17:27 GMT+0000 (UTC) https://dev.to/kowalevski/how-to-install-or-update-node-by-using-nvm-node-version-manager-1ip1

#javascript #nodejs #nvm #npm
star

Mon Jun 14 2021 12:11:52 GMT+0000 (UTC)

#heroku #nodejs #commandline
star

Mon Jun 07 2021 08:25:51 GMT+0000 (UTC)

#hbs #handlebars #express #nodejs
star

Sun Jun 06 2021 15:47:09 GMT+0000 (UTC) https://attacomsian.com/blog/nodejs-password-hashing-with-bcrypt

#bcrypt #authentication #express #nodejs #password
star

Sun Jun 06 2021 15:41:09 GMT+0000 (UTC) https://attacomsian.com/blog/mongoose-connect-async-await

#mongoose #mongodb #nodejs
star

Sun May 23 2021 14:30:42 GMT+0000 (UTC)

#nodejs #heroku #github
star

Fri May 21 2021 20:09:05 GMT+0000 (UTC)

#html #nodejs #pdf
star

Sat May 08 2021 17:59:57 GMT+0000 (UTC)

#jest #nodejs #testing
star

Sat May 08 2021 07:38:30 GMT+0000 (UTC)

#javascript #nodejs
star

Tue Apr 27 2021 22:51:13 GMT+0000 (UTC) wrote it myself

#nodejs
star

Wed Apr 21 2021 09:13:13 GMT+0000 (UTC)

#nodejs
star

Wed Mar 31 2021 12:07:26 GMT+0000 (UTC)

#nodejs #mongoose
star

Mon Mar 15 2021 13:40:38 GMT+0000 (UTC) https://github.com/mattdesl/gsx-pdf-optimize

#nodejs #commandline #npx
star

Thu Mar 11 2021 13:05:11 GMT+0000 (UTC)

#nodejs
star

Tue Mar 09 2021 15:29:16 GMT+0000 (UTC)

#nodejs
star

Wed Feb 24 2021 20:46:20 GMT+0000 (UTC) https://www.npmjs.com/package/ip

#nodejs #javascript
star

Sat Feb 06 2021 12:27:05 GMT+0000 (UTC)

#javascript #nodejs
star

Thu Jan 07 2021 22:05:21 GMT+0000 (UTC) https://www.reddit.com/r/node/comments/4txqqw/how_to_track_email_opens_with_nodejs_app/

#nodejs #javascript #email
star

Fri Dec 04 2020 01:43:47 GMT+0000 (UTC)

#nodejs,jquery #nodejs
star

Fri Dec 04 2020 01:42:13 GMT+0000 (UTC)

#nodejs #jquery
star

Fri Nov 27 2020 18:42:18 GMT+0000 (UTC) https://stackoverflow.com/questions/22636388/import-sql-file-in-node-js-and-execute-against-postgresql

#sql #nodejs
star

Sat Nov 14 2020 17:51:41 GMT+0000 (UTC)

#nodejs
star

Wed Nov 11 2020 12:56:36 GMT+0000 (UTC)

#json #nodejs #debug
star

Sat Oct 10 2020 17:41:42 GMT+0000 (UTC) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
star

Fri Oct 09 2020 23:22:52 GMT+0000 (UTC) https://github.com/716green/graphql-express-setup/blob/main/server.js

#nodejs #javascript #graphql #express
star

Sun Oct 04 2020 06:48:54 GMT+0000 (UTC)

#nodejs
star

Wed Aug 26 2020 21:29:30 GMT+0000 (UTC)

#nodejs #javascript
star

Sat Aug 22 2020 23:06:10 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:22:15 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:18:23 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:53:41 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:51:22 GMT+0000 (UTC)

#nodejs #javascript
star

Tue Aug 04 2020 22:56:30 GMT+0000 (UTC) https://flaviocopes.com/node-mass-rename-files/

#javascript #nodejs
star

Mon Jun 29 2020 22:48:29 GMT+0000 (UTC)

#gulp #nodejs
star

Mon Jun 08 2020 10:15:25 GMT+0000 (UTC) https://lavalite.org/blog/fastest-method-to-copy-file-in-nodejs

#nodejs #fs #javascript
star

Mon May 25 2020 10:06:38 GMT+0000 (UTC) https://stripe.com/docs/api/customers/create

#nodejs
star

Thu Apr 30 2020 06:35:49 GMT+0000 (UTC) https://www.toptal.com/nodejs/secure-rest-api-in-nodejs

#nodejs
star

Tue Apr 28 2020 19:40:32 GMT+0000 (UTC) https://medium.com/javascript-in-plain-english/querying-sql-server-in-node-js-using-async-await-5cb68acf2144

#javascript #nodejs
star

Tue Apr 28 2020 19:22:18 GMT+0000 (UTC) https://www.npmjs.com/package/express-session

#nodejs
star

Sun Apr 26 2020 20:50:22 GMT+0000 (UTC) https://api.jquery.com/jquery.post/

#javascript #nodejs
star

Sun Mar 29 2020 07:06:35 GMT+0000 (UTC) https://gist.github.com/trantorLiu/5924389

#javascript #nodejs #handlebars #express
star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

#javascript #nodejs #commandline

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension