Category: javascript
Category Added in a WPeMatico Campaign
Mocking my database functions globally with jest
See original post here for more context.
tl;dr, I had a database table with some functions (createOne, findOne etc) that I managed to mock in order to do some unit testing of my API.
Now I have multiple tables and a lot more tests to write, and the solution I have now generates a lot of code duplication when mocking the database functions in every test file. Therefore, I would now like to have the mocks available globally in all my test files.
I have read a lot about this on all different forums as well as checking the official docs but without success.
i have the following structure rn:
__tests__
pages
api
<api tests>
src
lib
database
table1.js
table2.js
__mocks__ (as per the official docs, this doesn't seem to work)
table1.js
table2.js
pages
api
<files under test that calls database functions>
and then example mock:
// __mocks__/table1.js
const table1 = jest.createMockFromModule("../table1");
table1.createOne = jest.fn().mockImplementation(async () => return {id: 1});
export default table1;
// __tests__/pages/api/route1
jest.mock("src/lib/database/table1");
import {createOne} from "src/lib/database/table1";
/* rest of testing like the original post */
But the mocks aren’t running correctly, and createOne is returning undefined. how do I make the mocks work globally?
How to add date function
I want to add (show too) 21 days to the 1st dose date if BioNTech was selected or add 28 days to the selected days if Sinovac was selected.
Enter your First name:
<br>
<input font-size="30px" style="padding:10px; width:500px;font-size:20px"type="text" name="FName" placeholder="Last Name">
<br>
<br />
Enter your Last name:
<br />
<input font-size="30px" style="padding:10px; width:500px;font-size:20px" type="text" name="LName" placeholder="First Name">
<br>
<br />
Enter your Contact number:
<br>
<input font-size="30px" style="padding:10px; width:500px;font-size:20px" type="text" name="ContactN" placeholder="Contact">
<br>
<br />
Enter the date of First Shot:
<br>
<input font-size="30px" style="padding:10px; width:500px; font-size:20px" type="date" name="DateR" value="dd/mm/yy">
<br>
<br />
Type of 1st Shot:
<p style="color: #C5C6C7">
<input style="font-size:20px" type="radio" name="Fshot" value="BionTech" checked> BioNTech    
<input style="font-size:20px" type="radio" name="Fshot" value="SinoVac"> SinoVac
</p>
</div>
</center>
<br /><br>
<input type="submit" style="font-size:22px" value="Book Now" class="hero-btn">
Lag when playing mic audio directly to output using web audio api
I simply want to play audio coming in the microphone directly to the output, using the code below. But there is a lag, about 0.2 seconds. Is there a way to reduce this delay ?
navigator.getUserMedia = navigator.getUserMedia ||navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var aCtx;
var analyser;
var microphone;
if (navigator.getUserMedia) {
navigator.getUserMedia(
{audio: true},
function(stream) {
aCtx = new AudioContext();
microphone = aCtx.createMediaStreamSource(stream);
var destination=aCtx.destination;
microphone.connect(destination);
},
function(){ console.log("Error 003.")}
);
}
Trusted Web Device Client
I have a public web API for a SaaS. We do not have user accounts for the users except for the admin, simply because the users who are using the system are often non-permanent workers or staff.
Instead we have a client/customer number and a PIN which is used to authenticate and setup the browser client. The authenticated JWT is stored in the browser like any other access token and is sent back to the server together with every API request. This works fine, although we do understand that a malicious actor could potentially extract this JWT and use it to illicitly authenticate as well.
Now we want to add two extra layers of security: IP whitelist and trusted devices.
First we have introduced an IP whitelist. This is straight-forward, we simply check the remote IP against a whitelist created by the admin which is bound to the client number.
Now the problem is with the trusted list of devices. For each client number, there should be a way to trust a device for that specific client number. So the client/customer should be able to use the web API only on the devices it has in the office. The ideal scenario would be that the admin can issue a “trusted device” certificate with a digital signature which sign something like “client number+year+client pin“. Then the local manager individual needs to import this certificate/secret manually on the device that should be trusted.
Then for each request our web client app (via javascript) also sends this signature with each request in a HTTP header. I understand this could potentially be spoofed as well but together with the IP whitelist we assess and believe it should be secure enough for this application.
The problem is now, how to implement that? As far as I understand:
- I cannot store such a secret in the browser because it might be cleared.
- I cannot read the filesystem with javascript. Store the secret in a text file?
- I cannot access the device certificate store.
How can I manage (import, store and read from javascript) this digital signature/certificate/secret in the client device? The web client can be anything from a iPad and Android phone to a Windows, Linux, iOS desktop. All web calls are done with SSL. We are not running any native app on the client device, only browser.
how to implement click logic
hi everyone!
i have a map with dots MAP which every 3 seconds shows a block with info
a function that is already in progress, and I want the function to stop when clicking on a point and display an infoblock for me(and i did it).
sorry in advance below is my code
// map with dots
var isActive = 0;
var isLoading = 1;
const count = document.querySelectorAll("[data-id]");//circle svg around dot
function removeClass() {
let infoCards = document.querySelectorAll("[data-info-id]");// info page name of the project
infoCards.forEach((el) => {
el.classList.remove("show");
});
}
function removeCircle() {
count.forEach((el) => {
el.style.display = "none";
});
}
function ready() {
function setAround(percent, idx) {
removeCircle();
let beforeElemIdx = idx === 0 ? count.length - 1 : idx - 1;
let beforeElem = document.querySelector(
'[data-id="' + beforeElemIdx + '"]'
);
let elem = document.querySelector('[data-id="' + idx + '"]');
elem.style.display = "block";
elem.classList.remove('active-circle');
beforeElem.style.display = "block";
const math = 2 * Math.PI * elem.r.baseVal.value;
elem.style.strokeDasharray = `${math} 1000`;
let a = math * (1 - percent / 100);
elem.style.strokeDashoffset = a;
if (percent >= 99.5) {
removeClass();
let infoShow = document.querySelector(`[data-info-id="${idx}"]`);
infoShow.classList.add("show");
isLoading++;
if (isLoading === count.length) {
isLoading = 0;
}
}
}
requestAnimationFrame(draw);
function draw(t) {
let idx = isLoading;
requestAnimationFrame(draw);
setAround((t / 30) % 100, idx);//timer 3sec
}
}
document.addEventListener("DOMContentLoaded", ready);
and i did this
var dots = document.querySelectorAll(".dota");
var infoCards = document.querySelectorAll("[data-info-id]");
let circle = document.querySelectorAll('[data-id]');
dots.forEach((el) => {
el.addEventListener('click', () => {
let idx = el.dataset.dota;
let circle = el.dataset.dota;
showInfo(idx);
addCircle(idx);
});
});
function showInfo(idx) {
removeClass();
let elem = document.querySelector(`[data-info-id='${idx}']`);
elem.classList.add('show');
}
function addCircle(idx) {
let circle = document.querySelector(`[data-id='${idx}']`);
circle.classList.add('active-circle');
}
and if u want my site pls dm me i’ll send my github page
TY ALL!
select>multiple fields when I write on DepartmentID then text show on CompanyID
function getSelect2MultipleSelection(htmlControlId) {
let returnValue = new Array();
let selectedValue = $(#${htmlControlId}).val();
$.each(selectedValue, function (i, v) {
let values = v.split(',');
$.each(values, function (j, k) {
returnValue.push(k);
});
});
return returnValue;
}
<div class="col-sm-4">
<div class="form-group">
<label asp-for="CompanyID"></label>
<select class="form-control form-control-sm" asp-for="CompanyID" multiple="multiple" asp-items="Model.DDLCompany">
</select>
<span asp-validation-for="CompanyID" class="text-danger"></span>
</div>
</div>
React: How important it is to pass the event as parameter in the callback function?
<button
className="delete-btn"
onClick={(event) => props.deleteNote(event, note.id)}
>
The code above is for a button that when clicked, calls a function that is in another component and should pass note.id as its parameter.
To my understanding, when we need to pass a function with extra parameters as props, we need to pass the whole callback function as written above.
However, I tried this version of code that doesn’t include the event as the parameter for the callback function, and it seems to still work. Is there an important difference between the code snippets?
<button
className="delete-btn"
onClick={() => props.deleteNote(event, note.id)}
>
Create a Proxy for promises
I want to create a function PromiseProxy that returns a proxy that simplifies the way we access to promises that returns objects with other props or methods:
(async () => {
const p = Promise.resolve({
fizz: Promise.resolve({
fizz: 'buzz'
}),
foo: () => 'bar',
});
console.log('RAW PROMISE');
console.log(await p.then(x => x.fizz.then(x => x.fizz))); // 'buzz'
console.log(await p.then(x => x.foo())); // 'bar'
console.log('PROXY PROMISE');
const pp = PromiseProxy(p);
console.log(await pp.fizz.fizz); // 'buzz'
console.log(await pp.foo()) // 'bar'
})();
I’m working with node 16.10. I’ve managed to implement the pp.fizz.fizz behaviour. I can get pp.foo as a bound function but when I call pp.foo() the code breaks instead of returning 'bar'.
console.log(await pp.foo()) // 'bar'
^
TypeError: pp.foo is not a function
I’m debugging the code without finding out any clue about the problem.
This is my code implementation:
const isPromise = obj => typeof obj.then === 'function';
const PromiseProxy = (value) => {
if (typeof value === 'function') {
return FunctionProxy(value);
}
if (!value || typeof value !== 'object') {
return value;
}
if (isPromise(value)) {
return InternalPromiseProxy(value);
}
return ObjectProxy(value);
}
const bind = (target, prop) => {
if (typeof target[prop] === 'function') {
return target[prop].bind(target);
}
return target[prop];
}
const promiseHandler = {
get: (promise, prop) => {
if (prop === 'then') {
return bind(promise, prop);
}
return InternalPromiseProxy(
promise.then(target => PromiseProxy(bind(target, prop)))
);
},
}
const InternalPromiseProxy = (promise) => new Proxy(promise, promiseHandler);
const rawHandler = {
get: (target, prop) => PromiseProxy(bind(target, prop)),
};
const ObjectProxy = (value) => new Proxy(value, rawHandler);
const functionHandler = {
apply: (target, thisArg, args) => PromiseProxy(target.apply(thisArg, args)),
}
const FunctionProxy = (fn) => new Proxy(fn, functionHandler);
Thanks!
How to add search feature inside select tag without using
I want to a search bar to search the option in the option list. I want to do without adding any plugin for example: searchit, search2 or many more. I want to add using just javascript or bootstrap plugin only
<% @title="Add Supplier" %>
<div class="container">
<div class="row">
<div class="col-6 mx-auto my-auto">
<h1 class="center mt-4">Add supplier</h1>
<%= form_with(model: @supplier, local: true, data: { turbo: false }) do |f| %>
<%= render 'shared/error_messages' , object: f.object%>
<%= f.label :Company, class: 'required form-label'%>
<%= f.text_field :company_id, value:current_user.company.name, class: 'form-control', :readonly => true %>
<%= f.hidden_field :company_id, value: current_user.company.id %>
<%= f.label :first_name, class: 'required form-label' %>
<%= f.text_field :first_name, class: 'form-control', required: true %>
<%= f.label :last_name, class: 'required form-label' %>
<%= f.text_field :last_name, class: 'form-control', required: true %>
<%= f.label :username, class: 'required form-label' %>
<%= f.text_field :username, class: 'form-control', required: true %>
<%= f.label :email, class: 'required form-label' %>
<%= f.email_field :email, class: 'form-control', required: true %>
<%= f.label :phone_number, class: 'required form-label' %>
<%= f.text_field :phone_number, class: 'form-control', required: true%>
<button type='button' class = "btn btn-warning my-2" onclick="addMore()">Add Item</button>
<div id="original-inputs">
<div class="row">
<div class="col-4">
<%= f.label :item, class: 'required form-label'%>
<% items = Item.where(company_id: current_user.company.id)%>
<div>
<select class="form-select" searchable="Search here..." name="[supplier_item][item_ids][]">
<option></option>
<% items.each do |item| %>
<option value="<%= item.id %>">
<%= item.item_code %>
<%= item.name %>
</option>
<% end %>
</select>
</div>
</div>
<div class="col-4">
<%= f.label :location, class: 'required form-label' %>
<% locations = Location.where(company_id: current_user.company.id)%>
<%= text_field_tag "[supplier_item][location_ids][]", nil , {list: 'browser-location', class: 'form-control'} %>
<datalist id="browser-location" >
<% locations.each do |location| %>
<option value="<%= location.id %>">
<%= location.location_code %>
<%= location.name %>
</option>
<% end %>
</datalist>
</div>
<div class="col-4">
<%= f.label :supplier_price, class: 'required form-label' %>
<%= number_field_tag "[supplier_item][supplier_prices][]", nil, step: :any, class: 'form-control' %>
</div>
</div>
</div>
<div id="dynamic-inputs"></div>
<div class="d-grid gap-2 my-2">
<%= f.submit "Create Supplier", class: "btn btn-primary" %>
<%= link_to 'Back', suppliers_path, class: 'btn btn-success' %>
</div>
<% end %>
</div>
</div>
</div>
<script type="text/javascript">
function addMore(){
$("#dynamic-inputs").append($("#original-inputs").html())
}
</script>
This is the code. I also don’t want to use datalist tag because i need to send the item value to backend.I just want to add search bar inside the select tag
How do I make a div disappear after moving up and down the page using css animation and jquery
I have a div that moves up and down the page. I want it to disappear after animation is done like this https://diamondcryptodeal.com/en/
This is what i have done so far but it still wont disappear. I used Jquery to try to remove the div entirely after animation is done. Thanks.
html
<div class="earner-notification" id="earner-notification">
<div class="row">
<div class="col">
<span style="margin-bottom: 12px;"><img src="images/arts/earnerlogo.jpg" class="bitcoin-earner img-fluid w-25 rounded-pill" alt="">
</span>
</div>
<div class="col">
<span style="position: absolute;left:25%; top:10%; font-family:Georgia, 'Times New Roman', Times, serif; font-size: 0.7rem;">
<span class="lead fw-bold:250;">Earner</span>
<br/>Mohammed from <span style="text-transform: capitalize;">INDIA</span>
just earned <span class=" fw-bold:300;">$850.</span></span>
</div>
</div>
</div>
css
@keyframes earner {
0% {
transform: translateY(-100%);
opacity: 1;
}
50% {
transform: translateY(100%);
opacity: 1;
}
100% {
transform: translateY(-100%);
opacity: 0;
display: none;
}
}
.earner-notification{
position: absolute;
left: 0;
top: 125px;
font-size: 1rem;
width: 15rem;
height: 5rem;
margin-left: 1.5rem;
border: 2px solid #FF7F50;
border-radius: 9px;
background-color: #000000;
color: $white;
animation: earner 10s ease;
//animation-name: earner;
//animation-duration: 10s;
//animation-delay: -2s;
//animation-iteration-count: 3;
}
.bitcoin-earner{
position: absolute;
top: 25%;
left: 2%;
}
jquery
$('.earner-notification').bind('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(e) { $(this).remove(); });
How to access array from another .js file?
I want to get a (Very large) array from another file so it doesn’t take up space in my main js file but I cannot figure it out, I have spent about 2 – 3 days searching online but cannot find an answer that will work. I’ve tried answers from How to access js array defined in another js file aswell as many other sites but nothing is working.
// the js file with the array I want
wordList = [
"this",
"is",
"an",
"array"
]
// main js file
const word = wordList[Math.floor(Math.random() * wordList.length)];
Any help is appreciated 🙂
Upload Bulk Json Data Using PHP/Laravel
I have an .json data file that contains a bulk of data and i need to upload this file to the firestore without using firebase import option…
By using coding in PHP or Laravel or JS…..
All if statements true?
It appears that no matter how much debugging i attempt, every time i include an if statement inside of a function, they will always be processed as true. I have attempted to make the same function for 2 days now. Could this be a hardware bug?
Call a route and store the payload in a variable in laravel
So currently I have a page and I need to call a route and the json-response it returns I need to store it in a variable on my chat.blade page. I tried using {{route}} as you’ll see in the code but that wouldnt get me back to my chat.blade unless I added a redirect()->route() to /me but then I got stuck in a loop.
Any ideas would be helpful =)
chat.blade.php
<div class="content">
<head>
<script>
// quick javascript to act as a client to our web socket server
// to state the obvious, this has nothing to do with PHP; this is javascript
var conn = new WebSocket('ws://localhost:9000');
var meObj = {};
// some basic call back functions when certain events happen on the web socket server
// when we successfully connect, log a simple message
conn.onopen = function (e) {
meObj = {{ route('profiles-me') }};
console.log("Connected!");
};
--- readcted to keep it short ---
MeController.php
--- Redacted to keep it short ---
public function me()
{
/** @var User $user */
$user = Auth::user();
// Lets extract the APP_KEY string to decode it.
$appKeyString = explode(':', env('APP_KEY'));
$secret = base64_decode($appKeyString[1]);
$signature = hash('sha256', $user->name . $secret);
return response()->json([
'me' => [
'id' => $user->id,
'name' => $user->name,
'picture' => $user->picture,
'csrf_token' => csrf_token(),
'sig' => $signature,
]
]);
}
--- Redacted to keep it short ---
The route
Route::get('/me', [MeController::class, 'me'])->name('profiles-me')->middleware('auth:profile');
