• Skip to main content

Rokturis

Pie kā turēties

  • Full Stack
    • JavaScript
    • JS Snipets
    • CSS
    • Git
    • VS Code

Nov 13 2023

Backend API

Requirements:

  • Node.js
  • npm
  • Express https://expressjs.com/en/starter/installing.html
  • mongoose
  • Nodemon
  • Studio 3T https://studio3t.com/
  • JWT

Layers (las capas):

  • api/router.js
  1. api/clients/clients.router.js
  2. api/clients/clients.controller.js
  3. api/clients/clients.service.js
  4. api/clients/clients.repository.js
  • api/clients/clients.model.js

req un res always stays in the controller.

return res.json // always with return, otherwise keeps executing the code that follows.

Import – Export

import { hola, adios } from './exportConst.js'; // importing functions as object.
import * as exportConst from './exportConst.js'; // importing all. * is naming the object.
import whatEverName from './exportDefault.js'; // when there is only one function. Possible changing functions name.

Controller

The best practice for controllers is to keep them free of business logic. Their single job is to get any relevant data from the req object and dispatch it to services. The returned value should be ready to be sent in a response using res.

Make sure you don’t pass any web layer objects (i.e. req, res, headers, etc) into your services. Instead, unwrap any values like URL parameters, header values, body data, etc before dispatching to the service layer.

params => obligatory

query => optional.

query received as string (true if exist)

JWT

Written by meudza · Categorized: Uncategorized

Nov 11 2023

Mongo

Table in mongo is collection.

Row = document

Column = value (attribute)

cardinal (n, n) generates additional table.

Foreign Key (FK) Primary Key (PK)

https://josejuansanchez.org/bd/unidad-03-teoria/index.html#relaciones-con-cardinalidad-11

https://openwebinars.net/blog/como-realizar-la-normalizacion-de-bases-de-datos-y-por-que/

Normalization

Todos atributos tiene que ser indivisibles. street, nr, zip

Todo los atributos tiene que ser del mismo tipo en la misma columna.

no deben existir grupos de valores repetidos.

T3

db = db.getSiblingDB(“vet”);

db.getCollection(“animals”).find({},{name:true, _id:false});

animals = db.getCollection(“animals”).find({}).toArray()

clients = db.getCollection(“clients”).find({_id: animals[0].clientId})

newClients = db.getCollection(“clients”).find({}).toArray()

newClients[0]._id

newAnimals = db.getCollection(“animals”).find({clientId: newClients[0]._id})

newerClients = db.getCollection(“clients”).find({fName: “Janis”}).toArray()

newerAnimals = db.getCollection(“animals”).find({clientId: newerClients[0]._id})

newerClients = db.getCollection(“clients”).find({“document.number”:“555654LV”}).toArray() //

newerAnimals = db.getCollection(“animals”).find({“clientId”: newerClients[0]._id})

newerClients = db.getCollection(“clients”).find({“document.number”:/555/}).toArray() // parcial text search

newerAnimals = db.getCollection(“animals”).find({“clientId”: newerClients[0]._id})

Written by meudza · Categorized: Uncategorized

Nov 11 2023

Backend

Server

npm

node_modules

express

Layers

Router => Route definition

Controller =>

Service => services logic

Repository => calls to DB

Written by meudza · Categorized: Uncategorized

Oct 25 2023

DOM

<div id="root"></div>

Obtencion de elementos

const myElement = document.getElementById('myId'); // {}
console.log('getElementById(myId)', myElement);

const pElements = document.getElementsByTagName('p'); // []
console.log('getElementsByTagName(p)', pElements);

const superElements = document.getElementsByClassName('super'); // []
console.log('getElementsByClassName(super)', superElements);

const notSuperElements = document.getElementsByClassName('notSuper'); // []
console.log('getElementsByClassName(notSuper)', notSuperElements);

const queryElement = document.querySelector('p.super'); // {} returns first. 
// solo el primer elemento que encuentre
console.log('querySelector(p.super-class)', queryElement);

const allElements = document.querySelectorAll('p.super'); // [] returns all.
// todos los elementos que encuentre
console.log(allElements);

Modificacion elementos

const emptyDiv = document.getElementById('emptyDiv');

emptyDiv.innerText = 'Escribo en el div vacio'; // To display text
emptyDiv.innerHTML = 'Escribo en el div vacio'; // to display HTML
emptyDiv.innerHTML = '<h1>Escribo en el div vacio</h1>'; // to include mixed ex. svg

emptyDiv.id = 'changedDiv';

emptyDiv.style.color = 'blue'; // NO HACER
emptyDiv.setAttribute('accesskey', 'modifiedAccesskey');  // changing atributes. ex. class (class, dark)
emptyDiv.setAttribute('class', 'nocturne');
emptyDiv.classList.add('myClass');  // add a class 
emptyDiv.classList.remove('myClass'); // remove a class

Creacion / eliminacion elementos

const nestedDiv = document.createElement('div'); //create in Js
const nestedP = document.createElement('p'); // create in Js
nestedDiv.appendChild(nestedP); // enclava en html
emptyDiv.appendChild(nestedDiv); // enclava en html

const firstDiv = document.createElement('div'); // should be valid html element
firstDiv.id = 'firstDiv';
emptyDiv.insertBefore(firstDiv, nestedDiv); // (where, BeforeWhat)

const replacedP = document.createElement('p');
replacedP.id = 'replacedP';
emptyDiv.replaceChild(replacedP, firstDiv); // 
firstDiv.parentElement.replaceChild(replacedP, firstDiv);
//parentElement instead of replaceChild ex. we dont know the name for emptyDiv

emptyDiv.removeChild(replacedP);

Events

// https://developer.mozilla.org/en-US/docs/Web/Events
function onEventFunction(param) {  // param always is "event"
  console.log('onEventFunction', param);
}

function addEventListenerFunction(param) {
  console.log('addEventListenerFunction', param);
}

const myButton = document.getElementById('myButtonId');

myButton.onclick = onEventFunction;
myButton.addEventListener('click', addEventListenerFunction); // no"()" for function call as parameter

Formularios

function manageMinMax() {

const myInput = document.forms.myFormName.myInputName;  // the same as next line 
const myInput = document.forms['myFormName']['myInputName'];  // calls value instead of property

  const min = myInput.getAttribute('min'); // 0
  const max = myInput.getAttribute('max'); // 10

  const message = document.getElementById('message');
  if (message) {
    document.forms['myFormName'].removeChild(message); // remove cause every input change is parsed and validated.
  }

  if (parseInt(myInput.value) < parseInt(min)) {
    myInput.value = min;
    const p = document.createElement('p');
    p.id = 'message';
    // p.innerText = 'El número mínimo es ' + min;
    p.innerText = `El número mínimo es ${min}`;
    document.forms['myFormName'].appendChild(p);
  }

  if (parseInt(myInput.value) > parseInt(max)) {
    myInput.value = max;
    const p = document.createElement('p');
    p.id = 'message';
    p.innerHTML = 'El número máximo es ' + max;
    document.forms['myFormName'].appendChild(p);
  }
}

document.forms['myFormName']['myInputName'].addEventListener('change', manageMinMax);
onclick.dsd = functionName

‘HTML elements’ are like arrays but to use as array need to be converted to array with map().

Written by meudza · Categorized: Full Stack · Tagged: dom

Oct 12 2023

JS Snipets

Number verification

function getPrecioMostrar(price) {
    price = +price // just in case string: convert to nr
    if (typeof price != "number" || isNaN(price)) {
        return ("no es un formato correcto");
    } else {
        return (price.toFixed(2) + " €");  // fixed 2 decimals
    }
}
console.log(getPrecioMostrar("4asd"))

Math

function divide(a, b) {
    return a / b;   
}
console.log(divide(21,7)) // 3

The substring() Method

substring() extracts a part of a string:

let text = "Hello world!";
let result = text.substring(1, 4); // result: ell

The toFixed() Method

toFixed() converts a number to a string, rounded to a specified number of decimals:

let num = 5.56789;
let n = num.toFixed(2);

The split() Method

split() splits a string into an array of substrings, and returns the array:

let text = "How are you doing today?";
const myArray1 = text.split(" ");        //How,are,you,doing,today? 
const myArray2 = text.split(" ", 3);     //How,are,you

The slice() method

slice() extracts a part of a string and returns the extracted part:

let text = "Hello world!";
let result = text.slice(0, 5); // Hello
let result = text.slice(3);    // lo world!

Capitalize a word

const Led = {
    lampara1: "rojo",
    lampara2: "verde",
    lampara3: "azul"
}

const RGB = [
    Led.lampara1.charAt(0).toUpperCase() + Led.lampara1.slice(1),
    Led.lampara2.charAt(0).toUpperCase() + Led.lampara2.slice(1),
    Led.lampara3.charAt(0).toUpperCase() + Led.lampara3.slice(1)
]

ATM Function

const currencies = [500, 200, 100, 50, 20, 10, 5, 2, 1];
const maxCoin = 2;

function getFreshMoney(myMoney) {
  for (let i = 0; i < currencies.length; i++) {
    const currency = currencies[i];
    if (myMoney >= currency) {
      currency > maxCoin ? console.log(`|${currency}eur`) : console.log(`(${currency})eur`);
      if (myMoney -= currency) {
        if (myMoney >= currency) {
          i--; // keeps in the same length in case there are more than 1 of a kind
        }
      }
    }
  }
}
const myMoney = 1498;

getFreshMoney(myMoney);

Promt and string to number

function duplicaNumero() {
  let num = prompt ('Please enter a number');
  num = +num;
  if (isNaN(num)) {
    return ('Is this a number???');
  }
  return num *2;
}
console.log(duplicaNumero());

Written by meudza · Categorized: Full Stack · Tagged: js

  • Page 1
  • Page 2
  • Page 3
  • Go to Next Page »

Copyright © 2026 · Altitude Pro on Genesis Framework · WordPress · Log in