I have created a new next.js v13.2 app and it’s development server is not working. It is showing done after a few seconds
Can somebody please help
I tried installing it many times again and restarted my brand new laptop
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I have created a new next.js v13.2 app and it’s development server is not working. It is showing done after a few seconds
Can somebody please help
I tried installing it many times again and restarted my brand new laptop
I found that my script saves both objects within an object. But doesnt do it on one of the objects. Why is it saving duplication of all the clicked items within the clicked object? I cant continue with my code until I get the clicked items saved in one object each, without any inside duplication. I dont know where in my code I can find the issue. I have debuggd it so far that when it saves into the localStorage from main.js it its in one object each in setItems(). But when the checkout() is runned, the console.log shows duplication of the objects inside some of the objects, not all. Mostly its one object that is showed as it should, without inside duplications. Ill attach the scripts from main.js and cart.js.
main.js
const wrapper = document.querySelector('.grid')
let lager = 10
let productsArray = []
let datavar = ''
async function getProducts(){
try{
const baseURL = 'https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/'
const url = baseURL + 'Products.json'
const response = await fetch(url)
let data = await response.json()
console.log(data)
productsArray.push(data)
datavar = Object.keys(data)
}catch(error){
console.log(error)
}
}
getProducts()
let cartNr = document.getElementById('cartNr')
const lang1 = document.querySelector('.lang1')
cartNr = 1
let products = [
{
id: 0,
namn: 'Sneaker1',
img: '1product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 1,
namn: 'Sneaker2',
img: '2product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 2,
namn: 'Sneaker3',
img: '3product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 3,
namn: 'Sneaker4',
img: '4product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 4,
namn: 'Sneaker5',
img: '5product',
pris: 1500,
lager: 10,
inCart: 0
}
]
const euro = document.querySelectorAll('.euro')
for(let i = 0; i < euro.length; i++ ){
euro[i].addEventListener('click', () => {
cartNumbers(products[i])
totalCost(products[i])
// totalStock(products[i])
})
}
function onLoadVartNumbers(){
let productNumbers = localStorage.getItem('cartNumbers')
if(productNumbers){
lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers}</div>`
}
}
function cartNumbers(product){
console.log('the product clicked is', product)
let productNumbers = localStorage.getItem('cartNumbers')
productNumbers = parseInt(productNumbers)
if(productNumbers){
localStorage.setItem('cartNumbers', productNumbers + 1)
lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers +1}</div>`
}else{
localStorage.setItem('cartNumbers', 1 )
lang1.innerHTML = `<div id="cartNr">${cartNr = 1}</div>`
}
setItems(product)
}
function setItems(product){
let cartItems = localStorage.getItem('productsInCart')
cartItems = JSON.parse(cartItems)
console.log(cartItems) //funkar
if(cartItems != null){
if(cartItems[product.img] == undefined){
cartItems = {
...cartItems,
[product.img]: product
}
console.log(cartItems)
}
cartItems[product.img].inCart += 1
console.log(cartItems) //funkar
}else{
product.inCart = 1
cartItems = {
[product.img]: product
}
console.log(cartItems)//funkar
}
localStorage.setItem('productsInCart',JSON.stringify(cartItems))
console.log(localStorage.getItem('productsInCart'))
}
function totalCost(product){
let cartCost = localStorage.getItem('totalCost')
if(cartCost != null){
cartCost = parseInt(cartCost)
localStorage.setItem('totalCost', cartCost + product.pris)
}else{
localStorage.setItem('totalCost', product.pris)
}
}
async function patchPost(obj){
const baseURL = `https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/`
const url = baseURL + `Products.json`
const init = {
method: 'PUT',
body: JSON.stringify(obj),
headers: {
"Content-type": "application/json; charset=UTF-8",
}
};
const response = await fetch(url, init)
const data = await response.json()
console.log(data)
}
let obj = Object.values(products)
patchPost(obj)
console.log(obj)
onLoadVartNumbers()
cart.js
let products = [
{
id: 0,
namn: 'Sneaker1',
img: '1product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 1,
namn: 'Sneaker2',
img: '2product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 2,
namn: 'Sneaker3',
img: '3product',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 3,
namn: 'Sneaker4',
img: '4products',
pris: 1500,
lager: 10,
inCart: 0
},
{
id: 4,
namn: 'Sneaker5',
img: '5product',
pris: 1500,
lager: 10,
inCart: 0
}
]
function displayCart(){
let cartItems = localStorage.getItem('productsInCart')
cartItems = JSON.parse(cartItems)
let productGrid = document.querySelector('.grid')
let cartCost = localStorage.getItem('totalCost')
if(cartItems && productGrid){
productGrid.innerHTML = ''
Object.values(cartItems).map(item =>{
productGrid.innerHTML += `
<div class="product">
<span>Produkt: ${item.namn}
<div class="price">Pris: ${item.pris}kr</div>
<div class="quantity">Antal: ${item.inCart}</div>
<div class="total">Totalt: ${item.inCart * item.pris}kr</div>`
})
productGrid.innerHTML +=
`<div class="cartTotal">Cart Total:${cartCost}</div>`
productGrid.innerHTML += `<button onclick="emptyCart()">Empty cart</button>`
productGrid.innerHTML += `<button onclick="checkout()">Checkout</button>`
}
}
function emptyCart(){
let productGrid = document.querySelector('.grid')
productGrid.innerHTML = ''
}
displayCart()
//checkout
function checkout(id){
let cartItemsObj = localStorage.getItem('productsInCart')
cartItemsObj = JSON.parse(cartItemsObj)
console.log(cartItemsObj)
let cartArray = Object.values(cartItemsObj)
console.log(cartArray )
let index = ''
cartArray.map((item) =>{
index= item.id
console.log('DATA OBJ ID', index)
})
//index är undefined
async function patchPost(obj){
const baseURL = `https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/`
const url = baseURL + `Products${index}.json`
const init = {
method: 'PATCH',
body: JSON.stringify({obj}),
headers: {
"Content-type": "application/json; charset=UTF-8",
}
};
const response = await fetch(url, init)
const data = await response.json()
console.log(data)
}
cartArray.map(item =>{
let newLager = item.lager - item.inCart
console.log(newLager)
if(item.id === id){
}
return{
lager: newLager
}
})
let obj = cartArray.reduce(function(acc, cur, ndex) {
acc[ndex] = cur;
return acc[ndex];
}, {});
patchPost(obj)
console.log(obj)
}
this is how it looks in the console.log
where 1product has duplications from both 1product and 2 product. While 2product is saved normal.
I want to optimize the following function:
Given a binary image A[i, j], I want to find an array of n dots with position [x, y] such that the sum of the differences between A[i, j] and the sum over exp(-s * ((i - x)**2 + (j - y)**2)) (possibly capped at 1) is minimized. So basically I look for n dots such that folding with the Gauss kernel resembles the original image as close as possible.
My idea is the following:
Ideally, I’d like to do gradient descent, so for each [i, j] and for each dot, check how varying [x, y] contributes to the sum. Since this is very expensive, I loop over the dots and then sample from a Gauss distribution around their position. For each of those positions, I compute the loss function (difference between original image and my blurry approximation). After the loop, each dot moves a step in the according direction.
Since this is a stochastic process, I still have a lot of noise.
function bm(scl = 1) {
const r = Math.sqrt(-2 * Math.log(Math.random())) / scl;
const phi = 2 * Math.PI * Math.random();
return [r * Math.cos(phi), r * Math.sin(phi)];
}
const bell = (u, scl = 1) => Math.exp(-scl * (u[0] ** 2 + u[1] ** 2));
const url =
"https://upload.wikimedia.org/wikipedia/commons/5/5f/Siemens-logo.svg";
const dim = [180, 150];
const ratio = dim[0] / dim[1];
const getSamplePos = () => [
20 + Math.floor((dim[0] - 40) * Math.random()),
20 + Math.floor((dim[1] - 40) * Math.random())
];
const cvs = document.querySelector("canvas");
[cvs.width, cvs.height] = dim;
const ctx = cvs.getContext("2d");
const svg = document.querySelector("svg");
svg.setAttribute("width", dim[0]);
svg.setAttribute("height", dim[1]);
const n = 100;
const dots = Array.from({ length: n }, function (_, i) {
const sp = getSamplePos();
const q = [sp[0] / dim[1], sp[1] / dim[1]];
const p = [0, 0];
const el = svg.appendChild(
document.createElementNS("http://www.w3.org/2000/svg", "circle")
);
el.setAttribute("cx", sp[0]);
el.setAttribute("cy", sp[1]);
el.setAttribute("r", "10");
return { q, p, el };
});
function update(id) {
for (let { q, p } of dots) {
for (let _ = 0; _ < 10; _++) {
const nd = bm(20);
const sp = [q[0] + nd[0], q[1] + nd[1]];
const isp = [Math.floor(dim[1] * sp[0]), Math.floor(dim[1] * sp[1])];
const a =
0 <= isp[0] && isp[0] < dim[0] && 0 <= isp[1] && isp[1] < dim[1]
? id.data[4 * (dim[0] * isp[1] + isp[0]) + 3] / 255
: 0;
let sum = 0;
for (let { q: q1 } of dots) {
sum += bell([q1[0] - sp[0], q1[1] - sp[1]], 20);
}
sum /= 80;
const adiff = a - sum;
const qdiff = [sp[0] - q[0], sp[1] - q[1]];
p[0] += adiff * qdiff[0];
p[1] += adiff * qdiff[1];
}
}
for (let { q, p, el } of dots) {
q[0] += p[0] / 100;
q[1] += p[1] / 100;
p[0] = p[1] = 0;
el.setAttribute("cx", dim[1] * q[0]);
el.setAttribute("cy", dim[1] * q[1]);
}
}
const img = new Image();
img.crossOrigin = "anonymous";
img.src = url;
img.onload = function () {
ctx.drawImage(img, 0, -20);
const id = ctx.getImageData(0, 0, dim[0], dim[1]);
(function rec() {
// window.setTimeout(rec, 1000);
window.requestAnimationFrame(rec);
update(id);
})();
};
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<canvas></canvas>
<svg></svg>
<script type="module" src="src/index.js"></script>
</body>
</html>
I wonder if there are cheaper algorithms to achieve a better outcome? Should I try the NumPy/SciPy methods instead of coding everything by hand in JS?
I am using socket.io for my Node app. The socket connection within the app has been established but data does not get emitted from server to client.
Client & server are on different port (3000 & 8080)
**Client Side: **
client side connection:
const socket = io.connect('http://localhost:8080', {
rejectUnauthorized: false,
transports: ['websocket', 'polling'],
vary: origin,
})
const sendMessage =()=>{
socket.emit('SENDMSG',{message: 'hello'})
joinRoom()
}
useEffect(()=>{
socket.on("receive_msg", (data)=>{
new Audio(order).play()
console.log('data', data.ListOfOrders)
setTableItems(data.ListOfOrders)
});
}, [socket])
const joinRoom = ()=>{
socket.emit('join_room', email)
}
Server Side JS:
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server, {
cors:{
origin: `http://localhost:3000`,
methods: ['GET', 'POST'],
credentials: true,
transports: ['websocket','polling'],
},
allowEIO3: true
});
// Runs when Client connects
io.on('connection',(socket)=>{
socket.on('join_room', (data)=>{
console.log(data). <----------------This gets printed meaning connection established.
socket.join(data)
})
})
app.post('/placeorder', async(req,res)=>{
try {
const { ordersList, spiceLevel, name, id } = req.body
const searchRestaurant = await Restaurants.findOne({shopName: name}).populate('orders');
for (let order of ordersList){
let orderEntry = new Orders({
qty: order.qty,
food: order.itemName,
tableNo: id,
spiceLevel: spiceLevel,
discount: order.discount,
price: order.price,
remarks: order.remarks
})
await orderEntry.save()
searchRestaurant.orders.push(orderEntry._id)
await searchRestaurant.save();
}
const ListOfOrders = searchRestaurant.orders
**io.to(searchRestaurant.email).emit('receive_msg', {ListOfOrders})** -> Data not emitted
return res.status(200).send('Order has been placed')
} catch (error) {
return res.status(400).send('Something went wrong. Please go back or refresh your browser.');
}
})
Can anyone help me fix this ? Let me know if you need more details.
My receiver side socket is in useEffect hook if that matters.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
var PDFRenderingInProgress = false
var pdfDoc = null
var canvas = document.getElementById('the-canvas')
var ctx = canvas.getContext('2d');
var container = document.getElementById("div-container")
var url = 'https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Physics-WEB_Sab7RrQ.pdf';
var wheelTimeoutHandler = null;
var wheelTimeout = 250 //ms
function renderPage(scale) {
pdfDoc.getPage(1).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
if (!PDFRenderingInProgress) {
PDFRenderingInProgress = true
var renderTask = page.render(renderContext);
renderTask.promise.then(function() {
PDFRenderingInProgress = false
})
}
});
}
function zoomWithWheel(event) {
panzoom.zoomWithWheel(event)
clearTimeout(wheelTimeoutHandler);
wheelTimeoutHandler = setTimeout(function() {
canvas.style.transform = "scale("+1/panzoom.getScale()+")"
if (pdfDoc)
renderPage(panzoom.getScale());
}, wheelTimeout)
}
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
renderPage(1);
});
var panzoom = Panzoom(container)
container.parentElement.addEventListener('wheel', zoomWithWheel)
function select_pdf(){}
#the-canvas {
direction: ltr;
transform-origin: top left;
}
#div-container {
width: 400px;
height: 400px;
}
<button onclick="select_pdf()">Select Pdf</button>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@panzoom/[email protected]/dist/panzoom.min.js"></script>
<div id="div-container">
<canvas id="the-canvas"></canvas>
</div>
My demo display a PDF from a web URL which is var url = ‘https://d3bxy9euw4e147.cloudfront.net/oscms-prodcms/media/documents/Physics-WEB_Sab7RrQ.pdf’;, may I know how to change the Web_URL Link Upload to local files upload? The PDF can be panned and zoom using mouse, but the only challenge right now is I wish to select PDF from a local computer file using the Select Pdf button and not from a web URL? Can anyone give me some guidance on this? Any help will be very much appreciated 🙂
I am trying to create a game, however I am having some trouble when it comes to users dragging and dropping images that are embedded inside divs. I am currently using this tutorial to do this, however as I’m sure you can guess, it’s not working. I have attached my github repo below for testing purposes, currently you can ignore the python files as they are not relevant to this problem. If you find out how you can make this work, feel free to let me know, and if you need more information i’d be happy to provide it.
So basically, I have a div which contains the entire game called container. Within this div, there are a bunch of divs which contain the columns. Then inside these divs there are divs, which contain images inside of them. I am trying to move the div’s images from within the container div, ie move from one row to the next, or one column to the next. However, the “dropping” part doesn’t seem to be working. It for some reason doesn’t update it, even though I practically copy/pasted code from the W3 schools site.
I have recently amended my basket in my Django e-commerce site to take multiple variations of a product. I have got everything to work except the remove item method in views.py. It deletes all items with the same product ID. I can’t work out how to get the method to recognise that an item variation is in the basket. Here is my function from views.py:
def remove_from_basket(request, item_id):
"""Remove the item from the shopping basket"""
try:
product = get_object_or_404(Product, pk=item_id)
item = None
if 'product_item' in request.POST:
flavour = request.POST['product_flavour']
strength = request.POST['product_strength']
product_item = request.POST['product_item']
item = f'{item_id}_{flavour}_{strength}'
print(item)
basket = request.session.get('basket', {})
if item:
del basket[item_id]['items_by_variation'][item]
if not basket[item_id]['items_by_variation']:
basket.pop(item_id)
messages.success(request, (f'Removed 'f'{product.name} flavour {flavour.upper()} from your basket'))
print('test 1')
else:
basket.pop(item_id)
messages.success(request, f'Removed {product.name} from your basket')
print('test 2')
request.session['basket'] = basket
return HttpResponse(status=200)
except Exception as e:
messages.error(request, f'Error removing item: {e}')
return HttpResponse(status=500)
This was previously working with some Javscript in the Django html template. I have renamed the data attribute in the anchor tag and updated the JS. Here is the complete section of template code:
{% for item in basket_items %}
<tr>
<td class="p-3 w-25">
{% if product.image %}
<a href="{{ product.image.url }}" target="_blank">
<img class="img-fluid rounded" src="{{ item.product.image.url }}">
</a>
{% else %}
<a href="">
<img class="img-fluid rounded" src="{{ MEDIA_URL }}noimage.png">
</a>
{% endif %}
</td>
<td class="py-3">
<p class="my-0"><strong>{{ item.product.name }}</strong></p>
<p class="my-0"><strong>Flavour:
</strong>{% if item.product.has_flavours %}{{ item.flavour|upper }}{% else %}N/A{% endif %}
</p>
<p class="my-0"><strong>Strength:
</strong>{% if item.product.has_strength %}{{ item.strength|upper }}{% else %}N/A{% endif %}
</p>
<p class="my-0 small text-muted">SKU: {{ item.product.sku|upper }}</p>
</td>
<td class="py-3">
<p class="my-0">£{{ item.product.price }}</p>
</td>
<td class="py-3 w-25">
<form class="form update-form" method="POST" action="{% url 'adjust_basket' item.item_id %}" ">
{% csrf_token %}
<div class="form-group ">
<div class="input-group ">
<div class="input-group-prepend ">
<button class="decrement-qty btn btn-sm btn-black rounded-0 "
data-item_id="{{ item.item_id }} " id="decrement-qty_{{ item.item_id }} ">
<span>
<i class="fas fa-minus fa-sm "></i>
</span>
</button>
</div>
<input class="form-control form-control-sm qty_input " type="number "
name="quantity " value="{{ item.quantity }} " min="1 " max="99 "
data-item_id="{{ item.item_id }} " id="id_qty_{{ item.item_id }} ">
<div class="input-group-append ">
<button class="increment-qty btn btn-sm btn-black rounded-0 "
data-item_id="{{ item.item_id }} " id="increment-qty_{{ item.item_id }} ">
<span>
<i class="fas fa-plus fa-sm "></i>
</span>
</button>
</div>
{% if item.product.has_flavours and item.product.has_strength %}
<input type="hidden " name="product_item " value="{{ item.item }} ">
<input type="hidden " name="product_flavour " value="{{ item.flavour }} ">
<input type="hidden " name="product_strength " value="{{ item.strength }} ">
{% endif %}
</div>
</div>
</form>
<a class="update-link text-info "><small>Update</small></a>
<a class="remove-item text-danger float-right " id="remove_{{ item.item_id }} "
data-product_item="{{ item.item }} "><small>Remove</small></a>
</td>
<td class="py-3 ">
<p class="my-0 ">£{{ item.product.price | calc_subtotal:item.quantity }}</p>
</td>
</tr>
{% endfor %}
Here is just the anchor tag in question:
<a class="remove-item text-danger float-right " id="remove_{{ item.item_id }} " data-product_item="{{ item.item }} "><small>Remove</small></a>
And finally here is the script that should make it work:
<script type="text/javascript">
// Update quantity on click
$('.update-link').click(function (e) {
var form = $(this).prev('.update-form');
form.submit();
})
// Remove item and reload on click
$('.remove-item').click(function (e) {
var csrfToken = "{{ csrf_token }}";
var itemId = $(this).attr('id').split('remove_')[1];
var item = $(this).data('product_item');
var url = `/basket/remove/${itemId}`;
var data = {
'csrfmiddlewaretoken': csrfToken,
'product_item': item
};
$.post(url, data)
.done(function () {
location.reload();
});
})
</script>
I think I am missing something really simple and I think it’s to do with my if statement as when I print item to the console it returns None and so skips to the delete item by the id and not the items_by_variations dictionary.
I am trying to build a Chrome extension that writes in a Google Document using aGAPI object. I am getting 4 similar errors because CSP blocks them
Refused to load the script 'https://apis.google.com/js/api.js' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
I’ve tried creating an Offscreen Document in my service-worker like this:
async function createOffscreen() {
if (await chrome.offscreen.hasDocument()) return;
console.log('hi');
await chrome.offscreen.createDocument({
url: 'foreground.html',
reasons: ['USER_MEDIA'],
justification: 'testing',
});
}
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (
changeInfo.status == 'complete' &&
tab.status == 'complete' &&
tab.url != undefined
) {
if (tab.url.includes('https://docs.google.com/document')) {
await createOffscreen();
const queryParameters = tab.url.substr(35, 44); // gets current docs
await chrome.tabs.sendMessage(tabId, {
type: 'NEW',
videoId: queryParameters,
});
}
}
});
yet I get the same erros.
I was going through the closures definition in Mozilla and found this example –
function makeSizer(size) {
return function () {
document.body.style.fontSize = `${size}px`;
};
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
What I still don’t understand is that if I want to increase the font, I can still do it this way –
function makeSizer(size) {
document.body.style.fontSize = `${size}px`;
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
What is the concept of closures doing here? Why the extra inner function?
Please correct my understanding.
I am trying to make ripple effect of button, but my ripple is going out of button as you can see in below given snippet. I even set
overflow : hidden;
still it is going out. Please tell how to confine ripple inside button only.
document.getElementById("btn").addEventListener("mousedown",(e)=>{
var btn = document.getElementById("btn")
var ripple = document.createElement("span")
ripple.classList.add("ripple")
btn.appendChild(ripple)
ripple.style.animation = "ripple 500ms linear forwards"
ripple.style.top = e.clientY - 15 + "px";
ripple.style.left = e.clientX - 15 + "px";
setTimeout(()=>{
ripple.remove()
},500)
})
.modaljs-btn-green {
/* position: relative; */
padding: 10px;
font-size: 15px;
color: #28b32f;
font-weight: 600;
border: none;
outline: none;
border-radius: 2px;
transition: all 325ms;
cursor: pointer;
margin-left: 10px;
overflow: hidden;
}
.modaljs-btn-green:hover {
background-color: rgb(198, 255, 196);
}
.ripple{
border-radius: 50%;
position: absolute;
background-color: grey;
width: 50px;
height: 50px;
opacity: 0.5;
}
@keyframes ripple{
0%{
transform: scale(0);
opacity: 0.5;
}
100%{
transform: scale(3);
opacity: 0;
}
}
<button id="btn" class="modaljs-btn-green">LOGIN</button>
I am trying to do something like this When a user navigate to the all chats screen That user can see all the chats he/her done with the recevier profile image and username and with a lastmessage same as instagram, facebook etc with same logic How can i do this? currenclty when i am hitting the api it give me all messages of the user but how can i get one last message with sender and reciver username? only one single chat happen in the room?
the room id is unquie of every two users
In my user model i have a array name allmessages and inside that array i have multiple object and that object look like this
SenderId: "6409b78b270244cb1ab59927" RecieverId: "6408acffea1211618848c620" LastMessage: "Hey" RoomId: "6409b78b270244cb1ab599276408acffea1211618848c620" date: 1678523682468
router.post('/getmessages', async (req, res) => {
const { MyUserId } = req.body;
User.findOne({ _id: MyUserId })
.then(sender => {
let lastMessages = [];
for (let i = 0; i < sender.AllMessages.length; i++) {
let receiverId = sender.AllMessages[i].RecieverId;
User.findOne({ _id: receiverId })
.then(receiver => {
if (receiver) {
lastMessages.push({
lastMessage: sender.AllMessages[i].LastMessage,
senderUsername: sender.username,
senderProfileImg: sender.profileImg,
receiverUsername: receiver.username,
receiverProfileImg: receiver.profileImg
});
}
if (i === sender.AllMessages.length - 1) {
res.status(200).send(lastMessages);
}
})
.catch(err => {
console.log(err);
res.status(422).send(err.message);
});
}
})
.catch(err => {
console.log(err);
res.status(422).send(err.message);
});
});
This is what is coming what i hit the API: as you can see there is multiple same username how can I get only one sender and receiver username with only one lastmessage
[
{
"lastMessage": null,
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hey ",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hey. ",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hi",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Chii",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hi",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hey ",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hi ",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
},
{
"lastMessage": "Hey. ",
"senderUsername": "ProfileImecwaecageTeset",
"receiverUsername": "ProfileImecwaecageTeset"
}
]
I’m new to Express.js (and learning MERN stack), my api/auth endpoint is taking forever to response (it shows “Processing…” in thunder client but request never gets to an end) I know this can happen in Express.js but don’t know why this happens, if anyone knows please help!
index.js
const connectToMongo = require("./db.js")
const express = require('express')
connectToMongo()
const app = express()
const port = 3000
// middlewares
app.use(express.json())
// Available routes
app.use("/api/auth", require("./routes/auth") )
app.use("/api/notes", require("./routes/notes") )
app.listen(port, () => {
console.log(`Example app listening on port http://127.0.0.1:${port}`)
})
db.js
const mongoose = require("mongoose");
const mongoURI = "mongodb://0.0.0.0:27017"
const connectToMongo = async () => {
await mongoose.connect(mongoURI)
console.log("connected to MongoDB successfully")
}
module.exports = connectToMongo;
auth.js
const express = require("express")
const router = express.Router()
const User = require("../models/User")
const { body, validationResult } = require('express-validator');
router.post("/", [
body('username').isLength({ min: 3 }),
body("email").isEmail,
body('password').isLength({ min: 6 }),
], (req, res) => {
res.send("aa")
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user));
})
module.exports = router;
User model in mongoose
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
timestamp: {
type: Date,
required: true,
default: Date.now
}
});
module.exports = mongoose.model("user", UserSchema);
I have initial type like this:
type X = {
a: number;
b?: number;
}
And after transform it should look like this:
type Y = {
a: boolean;
b?: boolean;
}
Is it possible to create some generic type to do such kind of transformation?
Because everything I tried finally gave me types like:
{
a: boolean;
b: boolean; // not optional
}
// or
{
a: boolean;
b: boolean | undefined // not the same as needed result
}
// or
{
a: boolean;
b?: number; // correctly optional, but not boolean
}
I made a form in Google Sheets with JavaScript. With that form I write data to a sheet and make calculations that are also written to the sheet. The data are numbers with decimals. In the Netherlands, decimals are separated with a comma. The entered numbers are initially neatly written with a comma to the sheet. The calculation is just wrong. There the numbers are treated as if the decimal point is a thousand separator. When the same (entered) numbers are read again by the form, the comma is also regarded as a separator between thousands and Sheets places a dot and 000 at the end of the number. This causes it to be given a complete mess. I know it has to do with the difference between US and Dutch number formats but I can’t figure out how to fix this.
Has anyone encountered this problem before and was able to solve it? Or someone willing to look for a solution?
The output will be 7
const compose = (a, b) => (c) => a(b(c));
const sum = (num) => num + 1;
console.log(
compose(sum, sum)(5)
);