Snippets Collections
import {Client} from 'pg';
import dotenv from 'dotenv';
dotenv.config();

export const client = new Client({
    database: process.env.DB_NAME,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD
});

client.connect();

/--------.env file ------------/
DB_NAME=memo-wall
DB_USERNAME=gordon
DB_PASSWORD=gordon
let sessionMiddleware = expressSession({
  secret: 'Tecky Academy teaches typescript',
  resave: true,
  saveUninitialized: true,
});

app.use(sessionMiddleware);

io.use((socket, next) => {
  let req = socket.request as express.Request;
  let res = req.res!;
  sessionMiddleware(req, res, next as express.NextFunction);
});

io.on('connection', function (socket) {
    if(!socket.request.session.user){
        socket.disconnect()
    }
});
async function logout(req:express.Request,res:express.Response){
    if(req.session){
        delete req.session['user'];
    }
    res.redirect('/login.html');
}
import {Request,Response,NextFunction} from 'express';

export function isLoggedIn(req:Request,res:Response,next:NextFunction){
    if(req.session?.['user']){
        next();
    }else{
        res.redirect('/login.html');
    }
}
import * as bcrypt from 'bcryptjs';

const SALT_ROUNDS = 10;

export async function hashPassword(plainPassword:string) {
    const hash = await bcrypt.hash(plainPassword,SALT_ROUNDS);
    return hash;
};


export async function checkPassword(plainPassword:string,hashPassword:string){
    const match = await bcrypt.compare(plainPassword,hashPassword);
    return match;
}
app.post('/apple',(req,res)=>{
    // logic of adding apple.
    if(req.session){
        io.to(`user-${req.session['user'].id}`).emit("new-apple","Congratulations! New Apple Created!");
    }
    res.json({updated:1});
});

io.on('connection', function (socket) {
    ....
    if(socket.request.session['user']){
        socket.join(`user-${socket.request.session['user'].id}`);  
        // One common way is to join the socket to a room named by the `user.id` or other group information.
     }
});
import expressSession from 'express-session';
const app = express();

// Add this line
app.use(expressSession({
    secret: 'Tecky Academy teaches typescript',
    resave:true,
    saveUninitialized:true
}));
const sessionMiddleware = expressSession({
    secret: 'Tecky Academy teaches typescript',
    resave:true,
    saveUninitialized:true,
    cookie:{secure:false}
});

app.use(sessionMiddleware);

io.use((socket,next)=>{
    let req = socket.request as express.Request
    let res = req.res as express.Response
    sessionMiddleware(req, res, next as express.NextFunction
});
//...
io.on('connection', function (socket) {
    // You can set any values you want to session here.
    const req = socket.request as express.Request;
    req.session['key'] = 'XXX';
    // There is no auto save for session.
    socket.request.session.save();

    // You can also send data using socket.emit() although it is not very useful
    socket.emit('any-key','values');
    socket.on("disconnect",()=>{
        //... rest of the code
    })
});
import {Request,Response} from 'express';
import express from 'express';

const app = express();
app.use(express.urlencoded({extended:true}));
app.use(express.json());
import expressSession from 'express-session';
const app = express();

// Add this line
app.use(expressSession({
    secret: 'Tecky Academy teaches typescript',
    resave:true,
    saveUninitialized:true
}));
import express from 'express';
import {Request,Response} from 'express';

const app = express();

app.get('/',function(req:Request,res:Response){
    res.end("Hello World");
})

const PORT = 8080;

app.listen(PORT, () => {
    console.log(`Listening at http://localhost:${PORT}/`);
});
// create a schema
const eventSchema = new Schema({
  name: String,
  slug: {
    type: String,
    unique: true
  },
  description: String
});

// create the model
const eventModel = mongoose.model('Event', eventSchema);

// middleware -----
// make sure that the slug is created from the name
eventSchema.pre('save', function(next) {
  this.slug = slugify(this.name);
  next();
});

// function to slugify a name
function slugify(text) {
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}
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!
})();
function promiseWrapper(fn) {
    return (req, res, next) => {
         fn(req, res).catch(next);
    };
}
const fs = require('fs')

exports.download = (req, res, next) => {
  console.log('fileController.download: started')
  const path = req.body.path
  const file = fs.createReadStream(path)
  const filename = (new Date()).toISOString()
  res.setHeader('Content-Disposition', 'attachment: filename="' + filename + '"')
  file.pipe(res)
}
const appRoot = require('app-root-path')
const multer = require('multer')

const fileController = require(`${appRoot}/src/controllers/FileController.js`)
const INPUT_NAME = 'photos'

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'files')
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname + '-' + (new Date()).toISOString())
  }
})

const fileFilter = (req, file, cb) => {
  if (['image/png', 'image/jpg', 'image/jpeg'].includes(file.mimetype)) {
    cb (null, true)
  } else {
    cb (null, false)
  }
}



module.exports = (app) => {
  app.use(multer({storage: fileStorage, fileFilter: fileFilter}).single('photo'))
  app.post('/upload', fileController.upload)
  app.post('/download', fileController.download)
}
// 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}`)
})
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}`)
});
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;
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
star

Thu Aug 19 2021 19:17:02 GMT+0000 (UTC)

#express #typescript #socketio
star

Thu Aug 19 2021 18:56:09 GMT+0000 (UTC)

#express #typescript #socketio
star

Thu Aug 19 2021 18:54:54 GMT+0000 (UTC)

#express #typescript
star

Thu Aug 19 2021 18:54:07 GMT+0000 (UTC)

#express #typescript
star

Thu Aug 19 2021 18:50:18 GMT+0000 (UTC)

#express #b-crypt
star

Thu Aug 19 2021 18:45:47 GMT+0000 (UTC)

#typescript #express #socketio
star

Thu Aug 19 2021 17:58:13 GMT+0000 (UTC)

#typescript #express
star

Thu Aug 19 2021 17:55:11 GMT+0000 (UTC)

#typescript #express
star

Thu Aug 19 2021 17:52:21 GMT+0000 (UTC)

#typescript #express
star

Thu Aug 19 2021 17:51:17 GMT+0000 (UTC)

#typescript #express
star

Fri Jun 25 2021 09:23:36 GMT+0000 (UTC) https://stackoverflow.com/questions/30845416/how-to-go-back-1-folder-level-with-dirname

#path #javascript #express
star

Mon Jun 14 2021 12:21:17 GMT+0000 (UTC) https://scotch.io/courses/create-a-crud-app-with-node-and-mongodb/a-mongoose-model

#express #nodej #mongodb #mongoose #slug #url
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

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 Jun 14 2020 18:07:51 GMT+0000 (UTC) https://stackoverflow.com/questions/42943124/how-to-get-current-url-path-in-express-with-ejs/42943283

#javascript #express
star

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

#javascript #nodejs #handlebars #express

Save snippets that work with our extensions

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