Snippets Collections
๐Ÿ”น a. Exporting from a module
๐Ÿ“ File: mathUtils.js


// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;



๐Ÿ”น b. Importing in another file
๐Ÿ“ File: main.js


// main.js
import { add, subtract } from './mathUtils.js';

console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2
// ๐ŸŒŸ Object Destructuring
const student = {
    name: "Rahul",
    roll: 101,
    class: "10th"
};

const { name, roll } = student;

console.log("Name:", name);   // Rahul
console.log("Roll No:", roll); // 101

// ๐ŸŒˆ Array Destructuring
const fruits = ["apple", "banana", "mango"];

const [fruit1, fruit2] = fruits;

console.log("First Fruit:", fruit1);  // apple
console.log("Second Fruit:", fruit2); // banana
Prototypal Inheritance (Old Way)

function Animal(name) {
    this.name = name;
}

Animal.prototype.sayHello = function() {
    console.log("Hello, I'm " + this.name);
};

let dog = new Animal("Dog");
dog.sayHello(); // Output: Hello, I'm Dog




 Classes (New Way โ€“ ES6)

class Animal {
    constructor(name) {
        this.name = name;
    }

    sayHello() {
        console.log(`Hello, I'm ${this.name}`);
    }
}

let cat = new Animal("Cat");
cat.sayHello(); // Output: Hello, I'm Cat
//1. Create a custom API for Users data and add different endpoints in express server to perform CRUD  operations on the API.  Test the endpoints using POSTMAN. 
//2. Use EJS view-engine to display the dynamic response. Display the data read from REST API in the form of a table in EJS. 




const express=require("express");
const app=express();

app.use(express.json());
app.set("view engine","ejs");

let users=[
    
    {id:1,name:"Abhi",email:"abhi@gmail.com"},
       { id:2,name:"Vars",email:"Vars@gmail.com"}

    
]


app.get("/users",(req,res)=>{
    res.render('users',{users});
})

app.get("/users/:id",(req,res)=>{
    const user=users.find(u=>u.id===parseInt(req.params.id));
    if(!user) return res.json({message:"No user"});
    res.json(user);
})

app.post("/users",(req,res)=>{
    const {name,email}=req.body;
    const newUser={
        id:users.length+1,
        name:name,
        email:email
    };
    users.push(newUser);
    res.render('users',{users});
});

app.put("/users/:id",(req,res)=>{
    const user=users.find(u=>u.id===parseInt(req.params.id));
    if(!user) return res.json({message:"No user"});
    user.name=req.body.name;
    user.email=req.body.email;
    res.json(user);
})

app.delete("/users/:id",(req,res)=>{
    users = users.filter(u => u.id != req.params.id);
    res.render('users',{users});
})

app.listen(3000,()=>{
    console.log("Server listening");
})





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>Table</h2>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>name</th>
                <th>email</th>
            </tr>
        </thead>
       <tbody>
        <%users.forEach(user=>{ %>
            <tr>
                <td><%=user.id %></td>
                <td><%=user.name %></td>
                <td><%=user.email %></td>
            </tr>
        <% }) %>
       </tbody>
    </table>
</body>
</html>
https://chatgpt.com/share/6806ee63-d908-800e-96ea-a6b4640389c6


//1. Create a http server listening request at port 3000. Process the request to provide different type of resources as response. (HTML, TEXT, JSON, etc.).

//server.js


javascript
Copy
Edit
const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Welcome to the Home Page</h1>');
    } else if (req.url === '/text') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('This is plain text.');
    } else if (req.url === '/json') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ name: 'Node.js', type: 'runtime' }));
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 - Page Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});




//2. Create express server listening request at port 3000. Add different endpoints to provide access to the resources.

//app.js


javascript
Copy
Edit
const express = require('express');
const app = express();

// HTML response
app.get('/', (req, res) => {
    res.send('<h1>Welcome to Express Server</h1>');
});

// Plain text response
app.get('/text', (req, res) => {
    res.type('text').send('This is a plain text response.');
});

// JSON response
app.get('/json', (req, res) => {
    res.json({ language: 'JavaScript', framework: 'Express' });
});

// Start server
app.listen(3000, () => {
    console.log('Express server running at http://localhost:3000');
});
const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// In-memory storage for users (as a mock database)
let users = [
  { id: 1, name: 'Alice', age: 30, email: 'alice@example.com' },
  { id: 2, name: 'Bob', age: 25, email: 'bob@example.com' }
];

// GET all users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
  res.json(user);
});

// POST a new user
app.post('/users', (req, res) => {
  const { name, age, email } = req.body;

  // Simple validation
  if (!name || !age || !email) {
    return res.status(400).send('Please provide name, age, and email');
  }

  const newUser = {
    id: users.length + 1,
    name,
    age,
    email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT update user by ID
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');

  const { name, age, email } = req.body;

  // Update user fields
  user.name = name || user.name;
  user.age = age || user.age;
  user.email = email || user.email;

  res.json(user);
});

// DELETE user by ID
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send('User not found');

  const deletedUser = users.splice(userIndex, 1);
  res.json(deletedUser[0]);
});

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});


index.js
----------
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');

// Route to fetch users and render table
app.get('/users', async (req, res) => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const users = await response.json();
    res.render('users', { users });
  } catch (err) {
    res.status(500).send('Failed to fetch data');
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
const express = require('express');
const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Home route
app.get('/', (req, res) => {
  res.send('Welcome to the Home Page!');
});

// About route
app.get('/about', (req, res) => {
  res.send('<h2>This is the About Page</h2>');
});

// JSON Data route
app.get('/data', (req, res) => {
  const data = {
    name: 'Dev',
    course: 'Full Stack',
    status: 'Learning Express'
  };
  res.json(data);
});

// POST route
app.post('/submit', (req, res) => {
  const userData = req.body;
  res.send(`Data received: ${JSON.stringify(userData)}`);
});

// 404 for other routes
app.use((req, res) => {
  res.status(404).send('404 - Page not found');
});

// Start server
app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
const http = require('http');

const server = http.createServer((req, res) => {
  const url = req.url;

  if (url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Welcome to the Home Page');
  } else if (url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>About Us</h1><p>This is the about page.</p>');
  } else if (url === '/data') {
    const jsonData = {
      name: 'Dev',
      course: 'Node.js',
      status: 'Learning'
    };
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(jsonData));
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

// Start server on port 3000
server.listen(3000, () => {
  console.log('Server is listening on http://localhost:3000');
});
const fs = require('fs');

// Create a readable stream
const readableStream = fs.createReadStream('input.txt', 'utf8');

// Create a writable stream
const writableStream = fs.createWriteStream('output.txt');

// Pipe the readable stream into the writable stream
readableStream.pipe(writableStream);

// Optional: Log when done
readableStream.on('end', () => {
  console.log('Streaming complete. Data written to output.txt');
});
const fs = require('fs');
const path = require('path');

// Create directory
fs.mkdirSync(path.join(__dirname, 'output'), { recursive: true });

// Create text file
fs.writeFileSync(path.join(__dirname, 'output', 'note.txt'), 'This is a text file.');

// Create JSON file
const data = { name: 'Node', type: 'runtime' };
fs.writeFileSync(path.join(__dirname, 'output', 'data.json'), JSON.stringify(data, null, 2));
const os = require('os');

console.log(os.platform());
console.log(os.cpus());
console.log(os.freemem());


const path = require('path');

console.log(path.basename(__filename));
console.log(path.join(__dirname, 'files', 'test.txt'));


const util = require('util');

const wait = util.promisify(setTimeout);
wait(1000).then(() => console.log('1 second passed'));



const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', (name) => {
  console.log(`Hello, ${name}`);
});

emitter.emit('greet', 'Alice');
const math = require('./mathUtils');
console.log(math.add(5, 3));        // 8
console.log(math.subtract(9, 4));   // 5
async function getWeather(){

    let city=document.getElementById('city').value;
    
const response= await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=6a86468ac81fa36a5565acaaa9f651b5`)
const data = await response.json()

const {list}=data
var temparray=new Array()
for(let i=0;i<list.length;i=i+8){
    const {dt_txt,main:{temp,temp_min,temp_max}}=list[i]

    
    temparray.push(temp);
   console.log(`Date:${dt_txt},Temperature:${temp},Minimum_temp:${temp_min},Max_temp:${temp_max}`)




}
}
<!DOCTYPE html>
<html>
<head>
  <title>Fetch API Table</title>
  <style>
    
    th, td {
      border: 1px solid #999;
      padding: 8px 12px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>

<h2 style="text-align:center;">User Data Table</h2>

<table id="userTable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <!-- Data will be inserted here -->
  </tbody>
</table>

<script>
  fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {
      const tableBody = document.querySelector("#userTable tbody");

      data.forEach(user => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td>${user.id}</td>
          <td>${user.name}</td>
          <td>${user.email}</td>
          <td>${user.address.city}</td>
        `;
        tableBody.appendChild(row);
      });
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
</script>

</body>
</html>
function task(message, delay) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(message);
        resolve();
      }, delay);
    });
  }
  
  task("Task 1", 1000)
    .then(() => task("Task 2", 1000))
    .then(() => task("Task 3", 1000))
    .then(() => console.log("All tasks done (Promise Chaining)"));
    function task(message, delay) {
        return new Promise((resolve) => {
          setTimeout(() => {
            console.log(message);
            resolve();
          }, delay);
        });
      }
      
      async function runTasks() {
        await task("Task 1", 1000);
        await task("Task 2", 1000);
        await task("Task 3", 1000);
        console.log("All tasks done (Async/Await)");
      }
      
      runTasks();
      
function task1() {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("Task 1 done");
        resolve();
      }, 1000);
    });
  }
  
  function task2() {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("Task 2 done");
        resolve();
      }, 1000);
    });
  }
  
  task1()
    .then(() => task2())
    .then(() => {
      console.log("All tasks completed");
    });
  
function task1() {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("Task 1 done");
        resolve();
      }, 1000);
    });
  }
  
  function task2() {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("Task 2 done");
        resolve();
      }, 1000);
    });
  }
  
  task1()
    .then(() => task2())
    .then(() => {
      console.log("All tasks completed");
    });
  
<!DOCTYPE html>
<html>
<head>
  <title>XHR Test</title>
</head>
<body>
  <script>
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
    xhr.onload = function () {
      if (xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        console.log("Response Data:", data); // This should show the post object
        // Optional: shows a popup so you know it worked
        
      } else {
        console.error("Error: " + xhr.status);
      }
    };
    xhr.onerror = function () {
      console.error("Network error");
    };
    xhr.send();
  </script>
</body>
</html>
function mul(num,callback){
    callback(num*2);
}

function sub(num,callback){
   callback(num-3);
}

function add(num,callback){
   callback(num+10);
}

mul(2,(res)=>{
   sub(res,(sres)=>{
       add(sres,(ares)=>{
      console.log(ares) })
   })
})
// Higher-order function: takes a function as an argument
function greet(name, greetingFunction) {
    console.log(greetingFunction(name));
  }
  
  // Function passed as an argument
  function sayHello(name) {
    return `Hello, ${name}!`;
  }
  
  // Calling the higher-order function with a function as an argument
  greet('Alice', sayHello);  // Output: Hello, Alice!

  
  // Higher-order function that returns a function
function multiplier(factor) {
    return function(number) {
      return number * factor;
    };
  }
  
  // Using the higher-order function to create a new function
  const double = multiplier(2);  // A function that doubles the input
  const triple = multiplier(3);  // A function that triples the input
  
  console.log(double(5));  // Output: 10
  console.log(triple(5));  // Output: 15
  
  const numbers1 = [1, 2, 3, 4];

// map() takes a function and applies it to each element in the array
const doubled = numbers1.map(number => number * 2);

console.log(doubled);  // Output: [2, 4, 6, 8]

const numbers = [1, 2, 3, 4, 5];

// filter() takes a function and returns an array of elements that pass the condition
const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);  // Output: [2, 4]
// Create a symbol
const uniqueSymbol = Symbol('unique');

// Using a symbol as a key for an object
const obj = {
  [uniqueSymbol]: 'This is a unique value'
};

console.log(obj[uniqueSymbol]);  // Output: This is a unique value

// Symbols are guaranteed to be unique
const anotherSymbol = Symbol('unique');
console.log(uniqueSymbol === anotherSymbol);  // Output: false
// Generator function
function* countUpTo(max) {
    let count = 1;
    while (count <= max) {
      yield count;  // Pause and return the current count
      count++;
    }
  }
  
  // Using the generator
  const counter = countUpTo(3);
  console.log(counter.next().value);  // Output: 1
  console.log(counter.next().value);  // Output: 2
  console.log(counter.next().value);  // Output: 3
  console.log(counter.next().value);  // Output: undefined (no more values)
  
// Importing specific functions from math.js
import { add, subtract, PI } from './math.js';

console.log(add(2, 3));       // Output: 5
console.log(subtract(5, 3));  // Output: 2
console.log(PI);              // Output: 3.14159
const colors = ["red", "green", "blue"];
const [first, second] = colors;

console.log(first);  // Output: red
console.log(second); // Output: green


const person = { name: "Alice", age: 25 };
const { name, age } = person;

console.log(name); // Output: Alice
console.log(age);  // Output: 25

 
// Register Custom Post Type
function custom_ourproducts_post_type() {
    $labels = array(
        'name'                  => _x( 'Our Products', 'Post Type General Name', 'text_domain' ),
        'singular_name'         => _x( 'Our Product', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'             => __( 'Our Products', 'text_domain' ),
        'name_admin_bar'        => __( 'Our Product', 'text_domain' ),
        'archives'              => __( 'Our Product Archives', 'text_domain' ),
        'attributes'            => __( 'Our Product Attributes', 'text_domain' ),
        'parent_item_colon'     => __( 'Parent Product:', 'text_domain' ),
        'all_items'             => __( 'All Products', 'text_domain' ),
        'add_new_item'          => __( 'Add New Product', 'text_domain' ),
        'add_new'               => __( 'Add New', 'text_domain' ),
        'new_item'              => __( 'New Product', 'text_domain' ),
        'edit_item'             => __( 'Edit Product', 'text_domain' ),
        'update_item'           => __( 'Update Product', 'text_domain' ),
        'view_item'             => __( 'View Product', 'text_domain' ),
        'view_items'            => __( 'View Products', 'text_domain' ),
        'search_items'          => __( 'Search Product', 'text_domain' ),
        'not_found'             => __( 'Not found', 'text_domain' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
        'featured_image'        => __( 'Featured Image', 'text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
        'insert_into_item'      => __( 'Insert into product', 'text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this product', 'text_domain' ),
        'items_list'            => __( 'Products list', 'text_domain' ),
        'items_list_navigation' => __( 'Products list navigation', 'text_domain' ),
        'filter_items_list'     => __( 'Filter products list', 'text_domain' ),
    );
    $args = array(
        'label'                 => __( 'Our Product', 'text_domain' ),
        'description'           => __( 'Custom post type for our products', 'text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail' ),
        'taxonomies'            => array( 'product_category' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 15,
        'menu_icon'             => 'dashicons-cart',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'post',
        'rewrite' => array(
            'slug' => '%product_category%',
            'with_front' => false
        ),
    );
    register_post_type( 'ourproducts', $args );
}
add_action( 'init', 'custom_ourproducts_post_type', 0 );

// Register Custom Taxonomy
function custom_product_taxonomy() {
    $labels = array(
        'name'                       => _x( 'Product Categories', 'Taxonomy General Name', 'text_domain' ),
        'singular_name'              => _x( 'Product Category', 'Taxonomy Singular Name', 'text_domain' ),
        'menu_name'                  => __( 'Product Categories', 'text_domain' ),
        'all_items'                  => __( 'All Categories', 'text_domain' ),
        'parent_item'                => __( 'Parent Category', 'text_domain' ),
        'parent_item_colon'          => __( 'Parent Category:', 'text_domain' ),
        'new_item_name'              => __( 'New Category Name', 'text_domain' ),
        'add_new_item'               => __( 'Add New Category', 'text_domain' ),
        'edit_item'                  => __( 'Edit Category', 'text_domain' ),
        'update_item'                => __( 'Update Category', 'text_domain' ),
        'view_item'                  => __( 'View Category', 'text_domain' ),
        'separate_items_with_commas' => __( 'Separate categories with commas', 'text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove categories', 'text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
        'popular_items'              => __( 'Popular Categories', 'text_domain' ),
        'search_items'               => __( 'Search Categories', 'text_domain' ),
        'not_found'                  => __( 'Not Found', 'text_domain' ),
        'no_terms'                   => __( 'No categories', 'text_domain' ),
        'items_list'                 => __( 'Categories list', 'text_domain' ),
        'items_list_navigation'      => __( 'Categories list navigation', 'text_domain' ),
    );
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'public' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'show_in_nav_menus' => true,
        'show_tagcloud' => true,
        'rewrite' => array(
            'slug' => 'category',
            'with_front' => false,
            'hierarchical' => true
        )
    );
    register_taxonomy( 'product_category', array( 'ourproducts' ), $args );
}
add_action( 'init', 'custom_product_taxonomy', 0 );

// Filter the permalink to include taxonomy slug
function filter_ourproducts_permalink($post_link, $post) {
    if ( $post->post_type === 'ourproducts' ) {
        $terms = wp_get_post_terms($post->ID, 'product_category');
        if ( ! empty($terms) && ! is_wp_error($terms) ) {
            return str_replace('%product_category%', $terms[0]->slug, $post_link);
        } else {
            return str_replace('%product_category%', 'uncategorized', $post_link);
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'filter_ourproducts_permalink', 10, 2 );
//Insights Insallation
bench get-app insights //*For Latest Version
Or
bench get-app insights --branch version-3
bench --site site1.local install-app insights


//Print Designer Installation
bench get-app print_designer
bench --site site1.local install-app print_designer

//Studio Installation
bench get-app studio
bench --site site1.local install-app studio

//OR//
//Studio
bench get-app studio
bench new-site studio.localhost --install-app studio
bench browse studio.localhost --user Administrator

//Webshop Installation
bench get-app webshop
bench --site site1.local install-app webshop

//Builder Installation
bench get-app builder
bench --site site1.local install-app builder

//HRM Installation
bench get-app hrms --branch version-15
bench --site site1.local install-app hrms


//Install Payment Module//
bench get-app payments
bench --site site1.local install-app payments


//Chat Installation
bench get-app chat
bench --site site1.local install-app chat
SELECT 
  u.id AS student_id,
  u.firstname AS student_firstname,
  u.lastname AS student_lastname,
  u.phone AS student_phone,

  parent_user.id AS parent_id,
  parent_user.firstname AS parent_firstname,
  parent_user.lastname AS parent_lastname,
  parent_user.phone AS parent_phone,
  parent_profile.country AS parent_country,

  p.status AS relationship_status,
  u.created_at AS student_signup_unix
FROM user u
INNER JOIN parents p ON p.student_id = u.id
INNER JOIN user parent_user ON parent_user.id = p.parent_id
INNER JOIN user_profile parent_profile ON parent_profile.user_id = p.parent_id
WHERE u.type = 'student'
  AND u.created_at BETWEEN 1748818800 AND 1750460400
  AND (
    (
      NOT (
        parent_user.phone LIKE '234%' OR 
        parent_user.phone LIKE '080%' OR 
        parent_user.phone LIKE '081%' OR 
        parent_user.phone LIKE '070%' OR 
        parent_user.phone LIKE '090%' OR 
        parent_user.phone LIKE '091%'
      )
    )
    AND (
      LOWER(parent_profile.country) NOT IN ('nigeria') OR parent_profile.country IS NULL
    )
  );
0000000000000000000000000cbb3d0cdca75fd140c2dfacaf0658b08658b109000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000107b2273756363657373223a747275657d00000000000000000000000000000000
60a060405234801561000f575f80fd5b5060405161063538038061063583398101604081905261002e91610062565b6001600160a01b0382166080525f61004682826101c9565b505050610284565b634e487b7160e01b5f52604160045260245ffd5b5f8060408385031215610073575f80fd5b82516001600160a01b0381168114610089575f80fd5b602084810151919350906001600160401b03808211156100a7575f80fd5b818601915086601f8301126100ba575f80fd5b8151818111156100cc576100cc61004e565b604051601f8201601f19908116603f011681019083821181831017156100f4576100f461004e565b81604052828152898684870101111561010b575f80fd5b5f93505b8284101561012c578484018601518185018701529285019261010f565b5f8684830101528096505050505050509250929050565b600181811c9082168061015757607f821691505b60208210810361017557634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156101c4575f81815260208120601f850160051c810160208610156101a15750805b601f850160051c820191505b818110156101c0578281556001016101ad565b5050505b505050565b81516001600160401b038111156101e2576101e261004e565b6101f6816101f08454610143565b8461017b565b602080601f831160018114610229575f84156102125750858301515b5f19600386901b1c1916600185901b1785556101c0565b5f85815260208120601f198616915b8281101561025757888601518255948401946001909101908401610238565b508582101561027457878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b6080516103946102a15f395f8181605d015260c801526103945ff3fe608060405234801561000f575f80fd5b506004361061004a575f3560e01c8063097b73531461004e5780637dc0d1d0146100585780639bfca6e01461004e578063a4877ddd1461009c575b5f80fd5b6100566100b1565b005b61007f7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100a4610182565b604051610093919061020d565b6040516352367d1560e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906352367d15906100fd905f90600401610290565b602060405180830381865afa158015610118573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061013c9190610338565b6101805760405162461bcd60e51b8152602060048201526011602482015270109858dada5b99c81b9bdd081d985b1a59607a1b604482015260640160405180910390fd5b565b5f805461018e90610258565b80601f01602080910402602001604051908101604052809291908181526020018280546101ba90610258565b80156102055780601f106101dc57610100808354040283529160200191610205565b820191905f5260205f20905b8154815290600101906020018083116101e857829003601f168201915b505050505081565b5f6020808352835180828501525f5b818110156102385785810183015185820160400152820161021c565b505f604082860101526040601f19601f8301168501019250505092915050565b600181811c9082168061026c57607f821691505b60208210810361028a57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f60208083525f845481600182811c9150808316806102b057607f831692505b85831081036102cd57634e487b7160e01b85526022600452602485fd5b8786018381526020018180156102ea576001811461030057610329565b60ff198616825284151560051b82019650610329565b5f8b8152602090205f5b868110156103235781548482015290850190890161030a565b83019750505b50949998505050505050505050565b5f60208284031215610348575f80fd5b81518015158114610357575f80fd5b939250505056fea2646970667358221220aaf7197534a4c7abde5506281b0cfe4811c18140bc1da396e1566d1bb8e4528c64736f6c63430008140033
[{"inputs":[{"internalType":"address","name":"_oracle","type":"address"},{"internalType":"bytes","name":"_json","type":"bytes"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"beforeAddLiquidity","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"beforeRemoveLiquidity","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rawJson","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.0/ScrollTrigger.min.js"></script>

<script>
const slides = document.querySelectorAll('.slide');
let isMobile = window.innerWidth <= 768; // Assuming mobile width is 768px or less

slides.forEach((slide, i) => {
    let angle = isMobile ? i * 10 : (i * 10) - 10;
    gsap.to(slide, {
        rotation: angle,
        transformOrigin: "0% 2300px",
    });
});

let speed = isMobile ? 30 : 30; // Faster speed on mobile
ScrollTrigger.create({
    trigger: '.scroller',
    start: "top top",
    end: "bottom bottom",
    //markers: true,
    onUpdate: (self) => {
        gsap.to(slides, {
            rotation: (i) => {
                let baseAngle = isMobile ? i * 10 : (i * 10) - 10;
                return baseAngle - self.progress * speed;
            }
        });
    }
});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

var $ = jQuery

$(document).ready(function(){

$('.reboot-slider').each(function(){

var $this = $(this),
    currentSlide = 0,
    previousSlide = 0,
    slideNumber = $this.find('.reboot-side-slider .swiper-slide:not(.swiper-slide-duplicate)').length,
    barHTML = '',
    forward,
    textContainer = $this.find('.reboot-changing-widget')

for(var i=0; i<slideNumber;i++){

    barHTML += `<span class="dot"><span class="dot-number">${i+1}</span></span>`
}

$this.find('.reboot-bar .dot').remove()
$this.find('.reboot-bar').append(barHTML)
$this.find('.reboot-bar .dot').eq(0).addClass('active')

textContainer.each(function(){
    var texts = $(this).find('.elementor-widget').eq(0)
    texts.addClass('currentUp')
    $(this).css('--h', texts.height()+'px')
})

setTimeout(function(){
    $this.addClass('loaded')
    if($this.find('.reboot-side-slider .swiper-container-initialized, .reboot-side-slider .swiper-initialized').length){
        $this.find('.reboot-side-slider').addClass('loaded')
    }

    var init = setInterval(function(){
        if($this.find('.reboot-side-slider .swiper-container-initialized, .reboot-side-slider .swiper-initialized').length){

            $this.find('.reboot-side-slider').addClass('loaded')
            clearInterval(init)
        }
    },50)
}, 500)

var bgs = JSON.parse($this.attr('data-settings')).background_slideshow_gallery,
    bgHTML = '<div class="reboot-slider-background">'

if(bgs){
    bgs.forEach(function(background){
        bgHTML += `<img decoding="async" src="${background.url}"/>`
    })
}
bgHTML += '</div>'

$this.find('.reboot-slider-background').remove()
$this.prepend(bgHTML)

var backgrounds = $this.find('.reboot-slider-background img')

backgrounds.eq(0).addClass('currentForward')

setInterval(function(){
    currentSlide = $this.find('.reboot-side-slider .swiper-slide-active').attr('data-swiper-slide-index')
    if(previousSlide != currentSlide) {

        if( previousSlide < currentSlide ){
            forward = true
        }
        if( previousSlide > currentSlide ){
            forward = false
        }
        if( previousSlide == slideNumber - 1 && currentSlide == 0 ){
            forward = true
        }
        if( previousSlide == 0 && currentSlide == slideNumber - 1 ){
            forward = false
        }
        textContainer.each(function(){
            var texts = $(this).find('.elementor-widget')

            $(this).css('--h', texts.eq(currentSlide).height()+'px')

            texts.removeClass('prev next currentUp currentDown')
            backgrounds.removeClass('prev currentBackward currentForward')

            backgrounds.eq(previousSlide).addClass('prev')

            if(forward) {
                texts.eq(previousSlide).addClass('prev')
                texts.eq(currentSlide).addClass('currentUp')

                backgrounds.eq(currentSlide).addClass('currentForward')

            }else{
                texts.eq(previousSlide).addClass('next')
                texts.eq(currentSlide).addClass('currentDown')

                backgrounds.eq(currentSlide).addClass('currentBackward')
            }
        })

        $this.find('.reboot-bar .dot').removeClass('active')
        $this.find('.reboot-bar .dot').eq(currentSlide).addClass('active')
    }
    previousSlide = currentSlide
}, 500)

$this.find('.reboot-bar .dot').on('click', function(){

    var index = $(this).index()

    $this.find('.reboot-side-slider .swiper-pagination-bullet').eq(index).trigger('click')
    $this.find('.reboot-side-slider .swiper-container').trigger('mouseleave')

})
$this.find('.reboot-slider-left').on('click', function(){

    $this.find('.reboot-side-slider .elementor-swiper-button-prev').trigger('click')
    $this.find('.reboot-side-slider .elementor-swiper').trigger('mouseleave')
})
$this.find('.reboot-slider-right').on('click', function(){

    $this.find('.reboot-side-slider .elementor-swiper-button-next').trigger('click')
    $this.find('.reboot-side-slider .elementor-swiper').trigger('mouseleave')
})
$this.find('.reboot-slider-left a, .reboot-slider-right a').on('click', function(e){

    e.preventDefault()
})

})
})

$(window).on('resize', function(){


$('.reboot-slider').each(function(){

    var textContainer = $(this).find('.reboot-changing-widget')

    textContainer.each(function(){
        var texts = $(this).find('.elementor-widget.currentUp, .elementor-widget.currentDown')

        $(this).css('--h', texts.height()+'px')
    })
})
})

</script>
selector{
    --radius: 8px;
    --height: 320px;
    --active-height: 410px;
    --overlay: 0.75;
}
selector{
    opacity: 0;
    transform: translateX(100px);
    transition: all 0.8s ease-in-out;
}
selector.loaded{
    opacity: 1;
    transform: translateX(0);
}

selector .swiper-wrapper{
    height: var(--active-height);
    align-items: center;
}
selector:not(.loaded) .swiper-wrapper{
    transition-duration: 0s !important;
}
selector .swiper-slide{
    display: flex;
    align-items: flex-end;
    border-radius: var(--radius);
    height: var(--height);
    box-shadow: 0 0 50px rgba(0,0,0,0.15);
}
selector.loaded .swiper-slide{
    transition: all 0.3s ease-in-out 0.2s;
}
selector .swiper-slide.swiper-slide-active{
    height: var(--active-height);
}
selector .swiper-slide:before{
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    background: rgb(0,0,0);
    background: linear-gradient(20deg, rgba(0,0,0,var(--overlay)) 0%, rgba(0,0,0,0) 100%);
    height: 100%;
    width: 100%;
    z-index: 1;
}
selector .elementor-testimonial__footer{
    display: block;
}
selector img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: var(--radius);
}
selector .elementor-testimonial__cite{
    z-index: 2;
    position: relative;
}
selector .elementor-testimonial__name{
    margin-bottom: 5px;
}
selector .swiper-pagination,
selector .elementor-swiper-button{
    display: none;
}
selector .swiper-container{
    overflow: hidden;
    margin-left: auto;
    margin-right: auto;
}

@media (max-width: 1024px){
selector{
    --height: 180px;
    --active-height: 250px;
}
}
@media (max-width: 767px){
selector{
    --height: 80px;
    --active-height: 105px;
    width: 100% !important;
    max-width: var(--container-widget-width, 300px) !important;
}
selector .elementor-testimonial__cite{
    opacity: 0;
}
}
selector{
    --speed: 0.5s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget .elementor-button{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev .elementor-button{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next .elementor-button{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp .elementor-button{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown .elementor-button{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
selector{
    --speed: 0.5s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget p{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev p{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next p{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp p{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown p{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
selector{
    --speed: 0.8s;
    --gap: 40px;
}
selector{
    transition: all 0.3s ease-in-out;
    height: var(--h);
    --height: calc(var(--h) + var(--gap));
    overflow: hidden !important;
}
selector .elementor-widget{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
selector .elementor-widget .elementor-heading-title{
    transform: translateY(calc(-10 * var(--height)));
    transition: none !important;
}
selector .elementor-widget.prev .elementor-heading-title{
    animation: prev var(--speed) ease-in-out;
    transform: translateY(calc(-1 * var(--height)));
}
selector .elementor-widget.next .elementor-heading-title{
    animation: next var(--speed) ease-in-out;
    transform: translateY(var(--height));
}
selector .elementor-widget.currentUp,
selector .elementor-widget.currentDown{
    z-index: 1;
}
selector .elementor-widget.currentUp .elementor-heading-title{
    animation: currentUp var(--speed) ease-in-out;
    transform: translateY(0);
}
selector .elementor-widget.currentDown .elementor-heading-title{
    animation: currentDown var(--speed) ease-in-out;
    transform: translateY(0);
}

@keyframes prev {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(calc(-1 * var(--height)));}
}

@keyframes next {
  0%   {transform: translateY(0);}
  100%   {transform: translateY(var(--height));}
}

@keyframes currentUp {
  0%   {transform: translateY(var(--height));}
  100%   {transform: translateY(0);}
}

@keyframes currentDown {
  0%   {transform: translateY(calc(-1 * var(--height)));}
  100%   {transform: translateY(0);}
}
@media (max-width: 1750px) and (min-width: 1381px){
selector{
    padding-left: 8%;
    padding-right: 12%;
}
}
@media (max-width: 1380px) and (min-width: 768px){
selector{
    padding-left: 0.5%;
    padding-right: 5.5%;
}
}
selector{
    --dot-size: 23px;
    --line-color: #B0B7D04D;
    --dot-color: #B0B7D0;
    --dot-color-active: #B0B7D0;
    color: #fff;
    font-size: 13px;
    font-weight: bold;
}
selector{
    height: 80vh;
    height: var(--min-height);
    max-height: 80vh;
    min-height: 0 !important;
}
selector .dot{
    height: var(--dot-size);
    width: var(--dot-size);
    background: var(--dot-color);
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    transform: scale(0.3);
    transition: all 0.3s ease-in-out;
    cursor: pointer;
}
selector .dot-number{
    opacity: 0;
    transition: all 0.3s ease-in-out;
}
selector .dot.active{
    transform: scale(1);
    background: var(--dot-color-active);
}
selector .dot.active .dot-number{
    opacity: 1;
}
selector:before{
    content: "";
    position: absolute;
    top: 50%;
    height: calc(100% - 20px);
    max-height: 90vh;
    width: 1px;
    background: var(--line-color);
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

@media (max-width: 767px){
selector{
    transform: translateX(-50%);
    flex-wrap: nowrap !important;
}
selector:before {
    width: calc(100% - 20px);
    height: 1px;

}
}
selector{
    background: #fff;
    --background-speed: 0.5s;
}
selector .elementor-background-slideshow{
    display: none;
}
selector .reboot-slider-background,
selector .reboot-slider-background img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: all 1s ease-in-out;
}
selector .reboot-slider-background img{
    object-fit: cover;
    opacity: 0;
    transform: scale(1.1);
}
selector .reboot-slider-background img.prev,
selector .reboot-slider-background img.currentBackward,
selector .reboot-slider-background img.currentForward{
    opacity: 1;
    transform: scale(1.1);
}

selector .reboot-slider-background img.currentBackward,
selector .reboot-slider-background img.currentForward{
    z-index: 1;
    opacity: 1;
    animation: bgNext var(--background-speed) linear;
    transition: all 1s ease-in-out;
    transform: scale(1);
}

selector:before{
    z-index: 2;
}
selector > .elementor-element{
    z-index: 3;
}

selector .reboot-bar,
selector .reboot-slider-left,
selector .reboot-slider-right{
    opacity: 0;
    transition: all 0.8s ease-in-out;
}
selector.loaded .reboot-bar,
selector.loaded .reboot-slider-left,
selector.loaded .reboot-slider-right{
    opacity: 1;
}
/*selector .ds-slider-left a:focus,*/
/*selector .ds-slider-right a:focus{*/
/*    outline: none !important;*/
/*}*/

@keyframes bgNext {
  0%   {opacity: 0; transform: scale(1.1);}
  100%   {opacity: 1; transform: scale(1);}
}

@media (min-width: 768px){
selector .reboot-bar,
selector .reboot-slider-left,
selector .reboot-slider-right{
    position: relative;
}
}

@media (max-width: 1380px) and (min-width: 768px){
selector{
    padding-left: 4%;
    padding-right: 4%;
}
}

@media (max-width: 767px){
selector .reboot-slider-left{
    left: calc(50% - 300px/2) !important;
}
selector .reboot-slider-right{
    right: calc(50% - 300px/2) !important;
}
}
reboot-slider

reboot-bar

reboot-changing-widget

reboot-changing-widget

reboot-changing-widget

reboot-side-slider

reboot-slider-left

reboot-slider-right
import mongoose, { Schema, Document, Model } from "mongoose";
import Joi, { ObjectSchema } from "joi";

interface IBook extends Document {
  id: number;
  title: string;
  author: string;
  year: number;
  genre: string;
}

const bookSchema: Schema<IBook> = new Schema({
  id: { type: Number, required: true, unique: true },
  title: { type: String, required: true },
  author: { type: String, required: true },
  year: { type: Number, required: true, min: 1800, max: 2025 },
  genre: { type: String, required: true, minlength: 2 },
});

const Books: Model<IBook> = mongoose.model<IBook>("MyBooks", bookSchema);

const bookDataValidator: ObjectSchema = Joi.object({
  id: Joi.number().min(1).required(),
  title: Joi.string().required(),
  author: Joi.string().required(),
  year: Joi.number().min(1800).max(2025).required(),
  genre: Joi.string().min(2).required(),
});

async function fetchBooks(): Promise<IBook[] | Error> {
  try {
    return await Books.find({});
  } catch (err) {
    return err as Error;
  }
}

const queryPageSchema: ObjectSchema = Joi.object({
  page: Joi.number().integer().min(1).required(),
});

//pagination fetching
async function fetchBooksByPage(page: {page:number}): Promise<{ status: number; data: IBook[] | string }> {
  try {
    const totalBooks = await Books.estimatedDocumentCount();
    console.log(page);
    if (totalBooks < (page.page - 1) * 2) {
      return { status: 404, data: "Sorry, no page found!" };
    } else if (totalBooks === 0) {
      return { status: 404, data: "Sorry, no book is there!" };
    }
    const booksData = await Books.find({}).skip((page.page - 1) * 2).limit(2);
    return { status: 200, data: booksData };
  } catch (err) {
    return { status: 500, data: (err as Error).message };
  }
}

async function addBook(title: string, author: string, year: number, genre: string): Promise<IBook | string | Error> {
  try {
    const lastDocument = await Books.find().sort({ id: -1 }).limit(1);
    const newBookId = lastDocument[0]?.id + 1 || 1;
    
    const { error, value } = bookDataValidator.validate({
      id: newBookId,
      title,
      author,
      year,
      genre,
    });
    
    if (error) return "Incorrect Data!";
    
    const newBook = new Books(value);
    return await newBook.save();
  } catch (err) {
    return err as Error;
  }
}

async function getBook(id: number): Promise<IBook | string | null | any> {
  try {
    const book = await Books.findOne({ id });
    return book || "No Books by this ID";
  } catch (err: any) {
    return err as Error;
  }
}

async function editBook(id: number, bodyValue: Partial<IBook>): Promise<IBook | string | null | any> {
  try {
    const updatedBook = await Books.findOneAndUpdate({ id }, { $set: bodyValue }, { new: true });
    return updatedBook || "No Books found to update";
  } catch (err: any) {
    return err as Error;
  }
}

async function deleteBook(id: number): Promise<IBook | null | Error> {
  try {
    return await Books.findOneAndDelete({ id });
  } catch (err) {
    return err as Error;
  }
}

const booksCurd = { fetchBooks, fetchBooksByPage, addBook, getBook, editBook, deleteBook, queryPageSchema }
export default booksCurd;
import mongoose from "mongoose";
import { Request, Response, NextFunction } from "express";

const connectDB = async (): Promise<void> => {
    try {
        await mongoose.connect("mongodb://localhost:27017/bookDB", {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        } as mongoose.ConnectOptions);
        console.log("MongoDB connected!");
    } catch (err) {
        console.error("Error connecting to MongoDB:", err);
    }
};

const authenticationMiddleware = (req: Request, res: Response, next: NextFunction): void => {
    const authHeader = req.headers.authorization;
    if (authHeader) {
        const token = 'Bearer yesauth1234';
        if (token === authHeader) {
            next();
        } else {
            res.status(403).send("Invalid token");
        }
    } else {
        res.status(401).send("Authentication required");
    }
};

export { connectDB, authenticationMiddleware };
https://medium.com/the-andela-way/what-exactly-is-cors-and-how-to-handle-it-fc2e52e89a0

import express, { Request, Response, Application } from 'express';
import { connectDB, authenticationMiddleware } from '../mongoDB/bookLib_db';
import booksCurd from '../mongoDB/bookModel';

const app: Application = express();
const port: number = 6933;

app.use(express.json());
app.use(authenticationMiddleware);

// Connect to MongoDB
async function connectMongo(): Promise<void> {
    await connectDB();
}
connectMongo();

//Fetch all books or by page --- two books per page
app.get('/', async (req: Request, res: Response): Promise<any> => {
    try {
        if (req.query?.page) {
            const page = parseInt(req.query.page as string, 10);
            const { error, value } = booksCurd.queryPageSchema.validate({ page });
            
            if (error) {
                return res.status(400).json({ error: error.details.map(detail => detail.message) });
            }
            
            const booksDataResultPerPage = await booksCurd.fetchBooksByPage(value);
            return res.status(booksDataResultPerPage.status).json(booksDataResultPerPage.data);
        }
        
        const booksDataResult = await booksCurd.fetchBooks();
        return res.status(200).json(booksDataResult);
    } catch (error) {
        return res.status(500).json({ message: 'Internal Server Error', error });
    }
});

//Add a new book
app.post('/books', async (req: Request, res: Response): Promise<any> => {
    try {
        const { title, author, year, genre } = req.body;
        const savedBook = await booksCurd.addBook(title, author, year, genre);
        return res.status(201).json(savedBook);
    } catch (error) {
        return res.status(500).json({ message: 'Failed to add book', error });
    }
});

//Get a book by ID
app.get('/books/:id', async (req: any, res: Response): Promise<any> => {
    try {
        const findBook = await booksCurd.getBook(req.params.id);
        return res.json(findBook);
    } catch (error) {
        return res.status(500).json({ message: 'Failed to fetch book', error });
    }
});

//Update a book by ID
app.put('/books/:id', async (req: any, res: Response): Promise<any> => {
    try {
        const updatedBook = await booksCurd.editBook(req.params.id, req.body);
        return res.json(updatedBook);
    } catch (error) {
        return res.status(500).json({ message: 'Failed to update book', error });
    }
});

//Delete a book by ID
app.delete('/books/:id', async (req: any, res: Response): Promise<any> => {
    try {
        const deletedBook = await booksCurd.deleteBook(req.params.id);
        
        if (!deletedBook || Object.keys(deletedBook).length === 0) {
            return res.status(404).json({ message: 'No book found for deletion' });
        }
        
        return res.status(200).json(deletedBook);
    } catch (error) {
        return res.status(500).json({ message: 'Something went wrong, Internal Server Error!', error });
    }
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/feb");
const prodschema = new mongoose.Schema({ name: String, price: Number });

const mongooseSave = async () => {
	const prodmodel = mongoose.model("prodgooses", prodschema);
	let ent = new prodmodel({ name: "vinear wallet 1", price: 8000 });
	let result = await ent.save();
	console.log(result);
};
// mongooseSave();

const mongooseUpdate = async () => {
    const prodmodel = mongoose.model('prodgooses', prodschema);
    let ent = await prodmodel.updateOne({name: "vinear wallet"}, {$set:{price :9500}});
}
// mongooseUpdate();

const mongoosedel = async () => {
    const prodmodel = mongoose.model('prodgooses', prodschema);
    let ent = await prodmodel.deleteOne({name: 'vinear wallet 1'});
}
// mongoosedel();

const mongoosefind = async () => {
    const prodmodel = mongoose.model('prodgooses', prodschema);
    let ent = await prodmodel.find();
    console.log(ent);
}
mongoosefind();
star

Tue Apr 22 2025 19:53:14 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:51:37 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:50:39 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:49:09 GMT+0000 (Coordinated Universal Time)

@signup

star

Tue Apr 22 2025 19:47:28 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/6806ee63-d908-800e-96ea-a6b4640389c6

@signup

star

Tue Apr 22 2025 18:37:20 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:36:46 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:36:06 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:35:23 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:30:07 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:28:15 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:27:32 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:26:44 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:24:06 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:23:05 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:22:15 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:21:15 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 18:15:31 GMT+0000 (Coordinated Universal Time)

@fsd

star

Tue Apr 22 2025 12:29:47 GMT+0000 (Coordinated Universal Time) https://appticz.com/ola-clone

@davidscott #appticz #olaclone

star

Tue Apr 22 2025 11:00:31 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/68076ce2-eafc-800b-8256-7210bec82b6a

@Bh@e_LoG

star

Tue Apr 22 2025 09:53:08 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/cryptocurrency-market-making-software/

@CharleenStewar ##marketmakingsoftware ##cryptotradingtools ##cryptoliquidity ##cryptoexchangesoftware

star

Tue Apr 22 2025 05:11:07 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Tue Apr 22 2025 03:49:04 GMT+0000 (Coordinated Universal Time)

@IfedayoAwe

star

Tue Apr 22 2025 02:22:31 GMT+0000 (Coordinated Universal Time) https://etherscan.io/verifyContract-solc?a

@mathewmerlin72

star

Tue Apr 22 2025 02:22:25 GMT+0000 (Coordinated Universal Time) https://etherscan.io/verifyContract-solc?a

@mathewmerlin72

star

Tue Apr 22 2025 02:22:20 GMT+0000 (Coordinated Universal Time) https://etherscan.io/verifyContract-solc?a

@mathewmerlin72

star

Tue Apr 22 2025 02:22:17 GMT+0000 (Coordinated Universal Time) https://etherscan.io/verifyContract-solc?a

@mathewmerlin72

star

Tue Apr 22 2025 01:35:17 GMT+0000 (Coordinated Universal Time) https://lifeonablock.com/spin-code/

@websplach #css

star

Tue Apr 22 2025 01:35:17 GMT+0000 (Coordinated Universal Time) https://lifeonablock.com/spin-code/

@websplach #javascript

star

Mon Apr 21 2025 23:40:01 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Mon Apr 21 2025 09:21:57 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/cryptocurrency-wallet-development-company/

@CharleenStewar #multichain #multichain wallet #cryptowallet #cryptomanagement

star

Mon Apr 21 2025 05:59:48 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:39 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:35 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:31 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:28 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:24 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:22 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:18 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:59:10 GMT+0000 (Coordinated Universal Time) https://rebootwebsites.co.za/how-to-create-an-advanced-slider-with-card-carousel-in-elementor-wordpress-tutorial/

@websplach #javascript

star

Mon Apr 21 2025 05:22:43 GMT+0000 (Coordinated Universal Time)

@codejck

star

Mon Apr 21 2025 05:21:48 GMT+0000 (Coordinated Universal Time)

@codejck

star

Mon Apr 21 2025 05:20:51 GMT+0000 (Coordinated Universal Time)

@codejck

star

Mon Apr 21 2025 05:19:41 GMT+0000 (Coordinated Universal Time)

@codejck

Save snippets that work with our extensions

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