Snippets Collections
const express = require("express");
const { z } = require("zod");

const app = express();

app.use(express.json());

const LoginSchema = z.object({
  // In this example we will only validate the request body.
  body: z.object({
    // email should be valid and non-empty
    email: z.string().email(),
    // password should be at least 6 characters
    password: z.string().min(6),
  }),
});

const validate = (schema) => (req, res, next) => {
  try {
    schema.parse({
      body: req.body,
      query: req.query,
      params: req.params,
    });

    next();
  } catch (err) {
    return res.status(400).send(err.errors);
  }
};

app.post("/login", validate(LoginSchema), (req, res) => {
  return res.json({ ...req.body });
});

app.listen(1337, () => console.log(`> Ready on http://localhost:${1337}`));
const query = {}; // Your query conditions go here

const [resultData, totalCount] = await Promise.all([
  User.find(query)
    .skip((page - 1) * limit)
    .limit(limit),

  User.countDocuments(query),
]);

console.log(resultData);
console.log(totalCount);
/* 
`mongoose.connect` is used to establish a connection to a MongoDB database, while `mongoose.connection` provides access to the active connection and allows you to interact with the database through events and operations.
*/
// see all the methods (https://mongoosejs.com/docs/api/connection.html)

const database = mongoose.connection;
// dbname
database.useDb("users");
// collection name
const collection = database.collection("users");
const express = require('express');
const cors = require('cors');

// env
const port = process.env.PORT || 3000;

// server
const app = express();

app.use(cors());

// routes
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// start
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});



///////////////////////////////////////////
// https
/*
npm install -g mkcert
mkcert create-ca
mkcert create-cert

const https = require("https");
const fs = require("fs");

const options = {
    key: fs.readFileSync("./config/cert.key"),
    cert: fs.readFileSync("./config/cert.crt"),
};
https.createServer(options, app).listen(8080, () => {
    console.log(`HTTPS server started on port 8080`);
});

*/
import express from "express";
import express from "express";
import path from 'path';

const app = express();
const PORT = process.env.PORT || 5000;

app.get('/',(req,res)=>{
    res.sendFile(path.resolve('index.html'));  
})

app.listen(PORT,()=> console.log('server is running'));
import express from "express";
import path from 'path';

const app = express();
const PORT = process.env.PORT || 5000;

app.get('/',(req,res)=>{
    res.sendFile(path.resolve('index.html'));  
})

app.listen(PORT,()=> console.log('server is running'));
//import this
const { check, validationResult } = require("express-validator/check");

//validate this
router.post(
  "/",
  [check("name", "Please add name").not().isEmpty(),
  check("email", "Please include a valid email").isEmail(),
  check("password", "Please enter a password with 6 or more characters").isLength({ min: 6 })
],
  (req, res) => {
       const errors = validationResult(req);
           if (!errors.isEmpty()) {
               return res.status(400).json({ errors: errors.array() });
           }
         res.send("passed");
  }
);
app.delete('/expressions/:id',(req,res,next)=>{
      const eleIndex = getIndexById(req.params.id,expressions);
    if(eleIndex!==-1){
        expressions.splice(eleIndex,1);
        res.status(204).send(expressions[eleIndex]);
    }
    else{
        res.status(404).send();
    }
});
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

Sun Nov 05 2023 04:28:47 GMT+0000 (Coordinated Universal Time) https://www.imadatyat.me/guides/schema-validation-with-zod-and-expressjs

#javascript #express #zod #backend
star

Fri Sep 29 2023 07:53:20 GMT+0000 (Coordinated Universal Time)

#mongodb #mongoose #express
star

Wed Oct 26 2022 05:26:16 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #express
star

Wed Sep 28 2022 22:11:57 GMT+0000 (Coordinated Universal Time) https://github.com/expressjs/session#cookie

#sessions #express
star

Sat May 21 2022 17:34:22 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sat May 21 2022 17:31:39 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sat May 21 2022 17:27:26 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sat May 21 2022 17:25:09 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sat May 21 2022 17:18:43 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sat May 21 2022 17:18:41 GMT+0000 (Coordinated Universal Time)

#restapi #no #express
star

Sun Apr 17 2022 09:50:47 GMT+0000 (Coordinated Universal Time) express-validator

#express #javascript #nodejs
star

Sun Apr 03 2022 23:50:32 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/app-delete-how-to-use-delete-in-express-and-set-up-route-node/612ddb940032010015329851

#express
star

Sun Feb 20 2022 17:33:27 GMT+0000 (Coordinated Universal Time) https://egghead.io/q/express?access_state

#express
star

Thu Aug 19 2021 19:17:02 GMT+0000 (Coordinated Universal Time)

#express #typescript #socketio
star

Thu Aug 19 2021 18:56:09 GMT+0000 (Coordinated Universal Time)

#express #typescript #socketio
star

Thu Aug 19 2021 18:54:54 GMT+0000 (Coordinated Universal Time)

#express #typescript
star

Thu Aug 19 2021 18:54:07 GMT+0000 (Coordinated Universal Time)

#express #typescript
star

Thu Aug 19 2021 18:50:18 GMT+0000 (Coordinated Universal Time)

#express #b-crypt
star

Thu Aug 19 2021 18:45:47 GMT+0000 (Coordinated Universal Time)

#typescript #express #socketio
star

Thu Aug 19 2021 17:58:13 GMT+0000 (Coordinated Universal Time)

#typescript #express
star

Thu Aug 19 2021 17:56:37 GMT+0000 (Coordinated Universal Time)

#typescript #express #socketio
star

Thu Aug 19 2021 17:55:11 GMT+0000 (Coordinated Universal Time)

#typescript #express
star

Thu Aug 19 2021 17:52:21 GMT+0000 (Coordinated Universal Time)

#typescript #express
star

Thu Aug 19 2021 17:51:17 GMT+0000 (Coordinated Universal Time)

#typescript #express
star

Fri Jun 25 2021 09:23:36 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time) https://scotch.io/courses/create-a-crud-app-with-node-and-mongodb/a-mongoose-model

#express #nodej #mongodb #mongoose #slug #url
star

Tue Jun 08 2021 16:48:15 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

Mon Jun 07 2021 08:25:51 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

Mon Jun 07 2021 08:20:41 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

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

#bcrypt #authentication #express #nodejs #password
star

Sun Jun 06 2021 15:34:43 GMT+0000 (Coordinated Universal Time)

#nodejs #async #promises #express #javas
star

Tue Mar 30 2021 06:01:42 GMT+0000 (Coordinated Universal Time)

#javascript #node.js #express
star

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

#nodejs #javascript #graphql #express
star

Sat Sep 26 2020 11:03:32 GMT+0000 (Coordinated Universal Time)

#nodejs #express #heroku
star

Sun Jun 14 2020 18:07:51 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time) 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