Snippets Collections
const uuid = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

export default uuid;
const express = require('express');
const { body, sanitizeBody, validationResult } = require('express-validator');

const app = express();

app.use(express.json());

// Define a route handler that uses request validation middleware
app.post('/register',
  body('username').trim().isLength({ min: 3, max: 30 })
    .withMessage('Username must be between 3 and 30 characters long')
    .escape(),
  body('email').trim().isEmail()
    .withMessage('Please enter a valid email address')
    .normalizeEmail(),
  body('password').isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters long')
    .matches(/\d/)
    .withMessage('Password must contain at least one number')
    .customSanitizer((value, { req }) => {
      // Hash the password before storing it in the database
      const hashedPassword = hashPassword(value);
      req.body.password = hashedPassword;
      return hashedPassword;
    }),
  (req, res) => {
    // Check for validation errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }

    // Sanitize input data
    sanitizeBody('username').escape();
    sanitizeBody('email').normalizeEmail();

    // Registration logic here
    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    const message = `Registered user: ${username} (${email}, ${password})`;
    res.send(message);
  });

// Start the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
// controllers/userController.js

const userModel = require('../models/userModel');

// Define route handling functions
function getAllUsers(req, res) {
  const users = userModel.getAllUsers();
  res.json(users);
}

function getUserById(req, res) {
  const id = req.params.id;
  const user = userModel.getUserById(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function createUser(req, res) {
  const newUser = req.body;
  const user = userModel.createUser(newUser);
  res.status(201).json(user);
}

function updateUser(req, res) {
  const id = req.params.id;
  const updatedUser = req.body;
  const user = userModel.updateUser(id, updatedUser);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function deleteUser(req, res) {
  const id = req.params.id;
  const user = userModel.deleteUser(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.send('User deleted successfully');
  }
}

// Export route handling functions
module.exports = {
  getAllUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser
};
// Here's how you can set up logging to a file:
// Install the winston package by running the following command in your terminal:
npm install winston

// Create a logger.js file in your project directory with the following code:
// This creates a logs folder in the same directory as your logger.js module,
// and places the log files inside it. You can adjust the logsDir variable 
// to specify a different directory if desired.

const path = require('path');
const winston = require('winston');
const { createLogger, format, transports } = winston;
const { combine, timestamp, printf } = format;

const logFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} ${level}: ${message}`;
});

const logsDir = path.join(__dirname, 'logs');

const logger = createLogger({
  level: 'info',
  format: combine(
    timestamp(),
    logFormat
  ),
  transports: [
    new transports.Console(),
    new transports.File({
      filename: path.join(logsDir, 'error.log'),
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    }),
    new transports.File({
      filename: path.join(logsDir, 'combined.log'),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    })
  ]
});

module.exports = logger;


// You can keep environment variables in a file, usually named .env, and load them
// into your Node.js application using a package like dotenv.
// 
// Here are the steps to do so:
// 
// Create a file named .env in the root of your project directory.
// 
// Add your environment variables to the .env file in the following format:

VARIABLE_NAME=variable_value

// For example:
MYSQL_USER=myuser
MYSQL_PASSWORD=mypassword

// Install the dotenv package by running the following command in your terminal:
npm install dotenv

// In your Node.js application, require the dotenv package at the top of your entry file (usually index.js), like this:
require('dotenv').config();

// Access your environment variables in your code using the process.env object. For example:

const mysqlUser = process.env.MYSQL_USER;
const mysqlPassword = process.env.MYSQL_PASSWORD;

// It's important to keep your .env file outside of your version control system,
// as it can contain sensitive information that you don't want to share with others.
// If you're using Git, you can add the .env file to your .gitignore file to
// prevent it from being committed.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config');
const userRouter = require('./routes/user');

const app = express();

// Set up middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Set up routes
app.use('/users', userRouter);

// Start the server
app.listen(config.port, () => {
  console.log(`Server listening on port ${config.port}...`);
});
const express = require('express');
const router = express.Router();
const user = require('../models/user');

// GET all users
router.get('/', async (req, res) => {
  try {
    const userList = await user.getAllUsers();
    res.json(userList);
  } catch (err) {
    console.error(err);
    res.status(500).send('Server error');
  }
});

// POST new user
router.post('/', async (req, res) => {
  try {
    const newUser = req.body;
    await user.addUser(newUser);
    res.status(201).send('User added');
  } catch (err) {
    console.error(err);
    res.status(500).send('Server error');
  }
});

module.exports = router;
const mysql = require('mysql');
const config = require('../config');

// Set up database connection
const connection = mysql.createConnection({
  host: config.mysqlUri,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: config.mysqlDBName,
});

// Connect to database
connection.connect((err) => {
  if (err) {
    console.error(`Error connecting to database: ${err.stack}`);
    return;
  }
  console.log(`Connected to database as id ${connection.threadId}`);
});

module.exports = {
  async getAllUsers() {
    return new Promise((resolve, reject) => {
      connection.query('SELECT * FROM users', (error, results, fields) => {
        if (error) {
          console.error(`Error retrieving users: ${error}`);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },

  async addUser(user) {
    return new Promise((resolve, reject) => {
      connection.query('INSERT INTO users SET ?', user, (error, results, fields) => {
        if (error) {
          console.error(`Error adding user: ${error}`);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },
};
module.exports = {
  port: process.env.PORT || 3000,
  mysqlUri: process.env.MYSQL_URI || 'mysql://localhost:3306',
  mysqlDBName: process.env.MYSQL_DB_NAME || 'my_database',
};
├── app.js
├── config/
│   ├── index.js
│   ├── development.js
│   ├── production.js
│   └── test.js
├── controllers/
│   ├── userController.js
│   └── ...
├── models/
│   ├── user.js
│   └── ...
├── routes/
│   ├── userRoutes.js
│   └── ...
├── services/
│   ├── userService.js
│   └── ...
└── utils/
    ├── logger.js
    └── ...
function uuid_v4() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}
star

Sat Jan 27 2024 01:36:58 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #number
star

Fri Apr 14 2023 09:18:26 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 09:11:10 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 09:05:57 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:55:14 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:51:06 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:50:38 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:49:15 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:48:51 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Fri Apr 14 2023 08:47:17 GMT+0000 (Coordinated Universal Time)

#javascript #uuid #guid
star

Sun Apr 09 2023 16:51:32 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid

#javascript #uuid #guid

Save snippets that work with our extensions

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