Given asynchronous function, need help trying to write a function to return new time limited version of input function

Here are the challenge directions:

Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function.

The time limited function should follow these rules:

  • If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.
  • If the execution of the fn exceeds the time limit, the time limited function should reject with the string “Time Limit Exceeded”.

I’ve tried these two bits of code:

// Function to return new time limited version of input function
const timeLimit = function(fn, t) {

    // Outer asynchronous function
    async function timeLimited(...args) {

        // Set start time to current time
        let startTime = Date.now()

        // Wait to get fulfillment value from function parameter
        const result = await fn(...args);

        // Duration will be current time minus the start time
        let duration = Date.now() - startTime;

        /* If duration is greater than the time parameter,
           throw time limit excession error */
        if (duration > t) throw new Error("Time Limit Exceeded");

        // Else return the result of the await function
        else return result;

    };

    // Return the asynchronous time-limited function
    return timeLimited; };

But I get this:

Output:

{"rejected":{},"time":100}

Expected:

{"rejected":"Time Limit Exceeded","time":50}
// Function·to·return·new·time·limited·version·of·input·function
const timeLimit = function(fn, t) {

    // Boolean to say error is false or true
    let hasError = false;

    // Outer asynchronous function
    async function timeLimited(...args) {

        // Set timer ID
        const timerId = setTimeout(() => hasError = true, t);

        // Constant to hold result
        const result = fn(...args);

        // Clear timeout
        clearTimeOut(timerId);

        // If there is an error, throw it
        if (hasError) throw new Error("Time Limit Exceeded");

        // Else return the result of the await function
        else return result;

    };

    // Return time limited function
    return timeLimited; };

But I get this:

Runtime Error

(node:21) Warning: Accessing non-existent property 'ListNode' of module exports inside circular dependency
(Use `nodejs run --trace-warnings ...` to show where the warning was created)
(node:21) Warning: Accessing non-existent property 'TreeNode' of module exports inside circular dependency
(node:21) Warning: Accessing non-existent property 'NestedInteger' of module exports inside circular dependency
node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
Node.js v20.10.0

Here are the test cases:

const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
limited(150).catch(console.log); // "Time Limit Exceeded" at t=100ms

If anyone could help me fix my code, I would appreciate it.

I have a problem with this project of mine that I did years ago [closed]

The project in question had to be a web page transformed into an offline web window, the problem is that the window works but if I use the task management mode it shows me that it is opening other sub-processes

I leave you the link to download the entire project. I hope that some of you can help me solve the problem

DOWNLOAD

I expect this problem to be resolved
problem

OnClick change image src from Json array JSX

I have a JSON array which contains some objects with image arrays and some with a single image .. example :

[  
   {
     "title": "Title",
     "img_src": "example.png"  
     },
   {
     "title": "Title2",
     "img_count": 2,
     "img_src": [
       "example2.png",
       "example3.png"
     ]  
   },
   {
     "title": "Title3",
     "img_src": "example4.png"  
     },
   {
     "title": "Title4",
     "img_count": 3,
     "img_src": [
       "example5.png",
       "example6.png",
       "example7.png"
     ]  
   }
]

Now, I’m showing the image in between two buttons, how can I change the image of a particular object (retrieved from JSON) through these buttons?

This is what I’ve done :

export default function Products({ jsonArr }) {
  const [counter, setCounter] = useState(0);

  function toggleImage(index) {
      setCounter(counter === 0 ? 1 : 0); //This is just for testing.
  }

.........
........

<div className="parentElement">
              {jsonArr.map((arrEl, i, _) => {
                return (
                  <div key={`${i}`} className="row" style={{ marginBottom: "50px" }}>
                    <div className="col-sm-4">
                      {arrEl.img_count && (
                        <button onClick={() => toggleImage(i)}>
                          <iconify-icon icon="ep:arrow-left-bold"></iconify-icon>
                        </button>
                      )}

                      {arrEl.img_count ? (
                        <img key={arrEl.title} src={arrEl.img_src[counter]} className="cover" height="250" width="250" alt="products"></img>
                      ) : (
                        <img key={arrEl.title} src={arrEl.img_src} className="cover" height="250" width="250" alt="products"></img>
                      )}
                      {arrEl.img_count && (
                        <button onClick={() => toggleImage(i)}>
                          <iconify-icon icon="ep:arrow-right-bold"></iconify-icon>
                        </button>
                      )}
                    </div>
...more code here...

I’m showing the buttons only when ‘img_count’ is present in an object. The ‘toggleImage’ button functionality is working but it’s changing the images of all the objects of an array.

Please suggest some better approach to do this. Or if this can be corrected.

React Spring useTransition rendering issue with dubplicate digits

I am using the useTransition hook from React Spring to animate an array of strings stored in an usestate.

The animation removes and vertically scrolls each digit, but when the array contains duplicate digits it removes and adds elements twice.

const [lista, setLis] = useState(['5', '0']);

const hour = useTransition(lista, {
  from: { opacity: 0, y: -50 },
  enter: { opacity: 1, y: 0 },
  leave: { opacity: 0, y: 50 },
  exitBeforeEnter: true,
  config: { duration: 400 },
});

{hour((style, cont) => (
  <animated.div style={style}>
    <h2 className="mb-0 text-warning" style={style}>
      {cont}
    </h2>
  </animated.div>
))}

I am aware this is due to how useTransition handles updates, but is there any way to bypass this
without needing to have a single useTransition for each digit?

Complete example Here

@Input model, how can I update the model fields without mapping one by one?

In an Angular Component (A PopUp) where you can configure tables and their respective Zones
enter image description here

These Zones are editable, and whenever you click on a edit icon in a zone row, a component is initialized under the respective row to edit the zone (allowing multiple edits to occur on the same page)
enter image description here

Right now, I manage to edit the zones, cancel the edits, but I don’t like my approach and am looking for suggestions.

Let me share the code first:

dialogue-ref-externe-table.component.html

          <p-table [paginator]="true" [rows]="40" [rowsPerPageOptions]="[20, 40, 60]"
                   [value]="refExterneZonesModified" [totalRecords]="refExterneZonesModified.length" styleClass="p-datatable-striped p-datatable-sm">
            <ng-template pTemplate="header">
              <tr>
                <th scope="col">Nom</th>
                <th scope="col">Type de la zone</th>
                <th scope="col">Position</th>
                <th scope="col">Longueur</th>
                <th scope="col">Sévérite Contrôle</th>
                <th scope="col">Obligatoire</th>
                <th scope="col">Cle</th>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>
            </ng-template>
            <ng-template pTemplate="body" let-zone>
              <tr>
                <td>
                  {{ zone.nom }}
                </td>
                <td>
                  {{ zone.type }}
                </td>
                <td>
                  {{ zone.position }}
                </td>
                <td>
                  {{ zone.longueur }}
                </td>
                <td>
                  {{ zone.severiteControle }}
                </td>
                <td>
                  <span *ngIf="zone.obligatoire">
                   <i class="pi pi-check" style="color: green"></i>
                  </span>
                </td>
                <td>
                  <span *ngIf="zone.cle">
                   <i class="pi pi-check" style="color: green"></i>
                  </span>
                </td>
                <td class ="action-column">
                  <button pButton type="button" icon="pi pi-pencil" class="p-button-rounded p-button-text action-button"
                          title="Modifier" style="color: black" (click)="editZone(zone)"></button>
                </td>
                <td>
                  <p-confirmDialog [style]="{ width: '50vw' }"></p-confirmDialog>
                  <button pButton type="button" icon="pi pi-trash" class="p-button-rounded p-button-text action-button"
                          title="Supprimer" style="color: black" (click)="deleteZone(zone.id)"></button>
                </td>
              </tr>
              <tr *ngIf="zone.saisieZone">
                <td colspan="9">
                  <app-saisie-zone [zoneModel]="zone"/>
                </td>
              </tr>
            </ng-template>
          </p-table>
        </p-fieldset>

ref-externe-zone-model.ts

      id?: number;
      refExterneTableId?: number;
      nom?: string;
      description?: string;
      type?: string;
      position?: number;
      longueur?: number;
      cle?: boolean;
      obligatoire?: boolean;
      severiteControle?: string;
      controles?: RefExterneControleModel[];
      saisieZone: boolean = false;

}

saisie-zone.component.ts

@Component({
  selector: 'app-saisie-zone',
  templateUrl: './saisie-zone.component.html',
  styleUrls: ['./saisie-zone.component.scss']
})
export class SaisieZoneComponent implements OnInit {

  @Input() zoneModel: RefExterneZoneModel = new RefExterneZoneModel();
  @Output() close: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() added: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() modified: EventEmitter<RefExterneZoneModel> = new EventEmitter<RefExterneZoneModel>();

  severitesControles: EnumRecord[] = [];
  typeDonnees: EnumRecord[] = [];
  valeurContraintes: EnumRecord[] = [];
  zoneModelModified = new RefExterneZoneModel();


  constructor(private enumService: EnumService) {
  }

  ngOnInit() {
    this.zoneModelModified = {...this.zoneModel};
    this.chargerEnums();
  }

  chargerEnums() {
      this.enumService.getEnum("SEVERITE_CONTROLE")?.subscribe(v => this.severitesControles = v);
      this.enumService.getEnum("TYPE_DONNEE")?.subscribe(v => this.typeDonnees = v);
      this.enumService.getEnum("VALEUR_CONTRAINTES")?.subscribe(v => this.valeurContraintes = v);
  }

  onConfirm() {
    this.zoneModel.id = this.zoneModelModified.id;
    this.zoneModel.refExterneTableId = this.zoneModelModified.refExterneTableId;
    this.zoneModel.nom = this.zoneModelModified.nom;
    this.zoneModel.description = this.zoneModelModified.description;
    this.zoneModel.type = this.zoneModelModified.type;
    this.zoneModel.position = this.zoneModelModified.position;
    this.zoneModel.longueur = this.zoneModelModified.longueur;
    this.zoneModel.severiteControle = this.zoneModelModified.severiteControle;
    this.zoneModel.obligatoire = this.zoneModelModified.obligatoire;
    this.zoneModel.cle = this.zoneModelModified.cle;
    //TODO Controles
    this.zoneModel.saisieZone = false;
  }

  onClose() {
    this.zoneModel.saisieZone = false;
  }

saisie-zone.component.html

<p-accordion [activeIndex]="0">
  <p-accordionTab header="Saisie de la zone: {{zoneModelModified.nom}}" >
      <p-fieldset legend="Attributes principaux">
        <div style="width: 50%; float: left">
            <label>Nom <label [style]="{ color: 'red' }">*</label></label>
            <input type="text" pInputText  [(ngModel)]="zoneModelModified.nom" class="p-field-element small-input-text" [style]="{ 'margin-left': '80px' }"/>
          <p></p>
            <label>Description</label>
            <textarea type="text" pInputText  [(ngModel)]="zoneModelModified.description" class="p-field-element" [style]="{ 'margin-left': '40px' }"></textarea>
          <p></p>
            <label>Position <label [style]="{ color: 'red' }">*</label></label>
            <input type="text" pInputText [(ngModel)]="zoneModelModified.position" class="p-field-element small-input-text" [style]="{ 'margin-left': '55px' }"/>
          <p></p>
            <label>Longueur <label [style]="{ color: 'red' }">*</label></label>
            <input type="text" pInputText [(ngModel)]="zoneModelModified.longueur" class="p-field-element small-input-text" [style]="{ 'margin-left': '45px' }"/>
        </div>
        <div style="width:50%; float: right">
          <p-checkbox [binary]="true" [(ngModel)]="zoneModelModified.cle"></p-checkbox>
          <label [style]="{ 'margin-left': '10px'}">Cle</label>
          <p></p>
          <p-checkbox [binary]="true" [(ngModel)]="zoneModelModified.obligatoire"></p-checkbox>
          <label [style]="{ 'margin-left': '10px'}">Obligatoire</label>
        </div>
      </p-fieldset>
      <p></p>
      <p-fieldset legend="Contrôles de la zone">
        <label>Sévérité des contrôles génériques <label [style]="{ color: 'red' }">*</label></label>
        <p-dropdown appendTo="body" [(ngModel)]="zoneModelModified.severiteControle" [options]="severitesControles" optionLabel="libelle"
                    optionValue="code" [style]="{ 'margin-left': '20px' }"/>
        <p></p>
        <label>Contrôle du type de donnée <label [style]="{ color: 'red' }">*</label></label>
        <p-dropdown appendTo="body" [(ngModel)]="zoneModelModified.type" [options]="typeDonnees" optionLabel="libelle"
                    optionValue="code" [style]="{ 'margin-left': '20px' }"/>
        <p></p>
        <label>Contrôle de valeurs</label>
        <p-dropdown appendTo="body" [options]="valeurContraintes" optionLabel="libelle"
                    [style]="{ 'margin-left': '20px' }" [showClear]="true" />
        <p></p>
        <button pButton type="submit" class="form-button" style="background-color: #0a7f5c; float: right; margin-left: 10px" title="ajouter"
                icon="pi pi-plus-circle" label="Confirmer" (click)="onConfirm()"></button>
        <button pButton class="form-button" style="background-color: rgb(128,128,128); float: right" title="annuler" icon="pi pi-times"
                label="Annuler" (click)="onClose()"></button>
      </p-fieldset>
  </p-accordionTab>
</p-accordion>

I don’t like the fact that I have to map all the modified fields in the zoneModelModified to zoneModel. I do that because if I do this.zoneModel = this.zoneModified, it won’t work, why? Because if I assign it like this and after that I do this.zoneModel.saisieZone = false, the saisie zone component won’t close. Based on this code, do you have any suggestion on how to improve this?

Thanks

Creating resolvers and typeDefs,models, I can’t seem to test if it works on not yet. Is it possible to have any clues if something seems wrong?

So I am about to graduate in my school, and I’m creating an ECommerce shop using GRAPHQL and MERN. Except the problem is I quite suck at GRAPHQL/MERN. I’m trying to grasp it. And i do quite get SOME stuff of it such as mutation and query BUT not in localhost:3001/GRAPHQL, but we simply started this last month… I’m not an expert at this but we HAVE to incorporate GRAPHQL and MERN in a project.
So I am trying my best to fix any issues myself and I have spent a whole entire day working on it. From morning to almost midnight, I can’t seem to figure out the issue when trying to create an ID. I’ve tried doing

createProduct: async(parent,{name,price,description}) => {
 return Product.create({name,price,description});
}

and incorporating the ID in updateProduct, instead.

updateProduct: async(parent,{id,name,price,description}) => {
return Product,fineOneandUpdate(
{_id: id},
{$set:{name,price,description}},
{new:true}
);}, // Comma to go to the deleteProduct
const resolvers = {
Query: {
  getProduct: async (parent, {productId}) =>{
    return Product.find.one({
      _id: productId //specific product
    });
  },
 getAllProduct: async() => {
  return Product.find({productId}); //empty ID might return all products
 }
 },
 Mutation:{
  createProduct: async(parent,{id,name,price,description}) => {
    return Product.create({id,name,price,description}); //mutation will create new product
  },
  updateProduct: async(parent,{id,name,price,description}) => {
    return Product.findOneAndUpdate( //mutation will update product
      {_id: id},
      {$set: {name,price,description}},
      {new: true}
    );
  },
  deleteProduct: async(parent,{id}) => {
    return Product.findOneAndDelete({_id: id}); //mutation will delete product
  }
 }
}
const {resolvers} = require('./resolvers');
const typeDefs = `
  type Product {
    _id: ID!
    name: String!
    price: Float!
    description: String!
  }
  
  type Query {
    getProduct(productId:ID!): Product
    getAllProduct: [Product]
  }
  type Mutation {
    createProduct(id: ID!,name: String!, price: Float!, description: String!): Product
    updateProduct(id: ID!, name: String!, price: Float!, description: String!): Product
    deleteProduct(id: ID!): Product
  }
`;

Then for the models, i have three files, index.js,items.js,Tech.js(Ignore this one).

The items.js file has

const { Schema, model } = require('mongoose');

const itemSchema = new Schema({
  item1: {
    id:{
      type: Number,
      required: true
    },
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
  item2: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
  item3: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
  item4: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
  item5: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
  item6: {
    name: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
  },
},
);

const Items = model('items', itemSchema);
module.exports = Items;

I’ve trying incorporating the ID in their too. But i can’t seem to tell what i’m doing wrong because in “localhost:3001/graphql”, i do

query Query($productId: ID!) {
  getProduct(productId: $productId) {
    _id
    name
    description
  }
}

and in return I get

{
  "data": {},
  "errors": [
    {
      "message": "Variable "$productId" of required type "ID!" was not provided.",
      "locations": [
        {
          "line": 1,
          "column": 13
        }
      ],
      "extensions": {
        "code": "BAD_USER_INPUT",
        "stacktrace": [
          "GraphQLError: Variable "$productId" of required type "ID!" was not provided."

Creating a custom booking product type with very specific logic for WooCommerce

I’m in need of a very specific booking/product behavior for WooCommerce. Here’s the gist:

  • customers can choose travel packages (= products)
  • the travel dates are fixed so no need for a date picker
  • the number of people per package is limited (eg. max 8 people can book it)
  • customers can book for multiple people
  • the packages include a choice of rooms (eg. single bed or twin bed), which are also limited (eg. there are 4 single bed and 2 twin bed rooms)
  • customers can book multiple rooms

I thought of extending the variable product type, making each room a variation, but I’m kinda stuck. I’d basically need a copy of the product type but extend it with a maximum number of people (maybe remodel the stock functionality for that), a custom logic that checks whether enough rooms have been selected for the number of people and a custom logic that checks which rooms are still available (where cancellations probably should make the rooms available again).

From my research I didn’t really find a way to copy the variable product type, make it a custom one and add the functionality.
Do you have a suggestion in how to do that?
Or did I maybe miss something entirely and there’s a plugin for that?

Zod’s superrefine doesn’t update errors dynamically

I have a form that uses both react-hook-form and Zod for validation.
the schema looks something like this:

 const schema = z
.object({
  email: z.string().email().optional(),
  userName: z.string().optional(),
  contactType: z.string(),
})
.superRefine((data, ctx) => {
    if (data.contactType === 'email' && !data.email) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['email'],
        message: 'email is required',
      });
    }else if {//more fields here}

  });

What usually happens with react-hook-form and Zod, is the following:

  1. You can type what you want, even if it’s a mistake, and validation is turned off
  2. The moment you submit the form, validation occurs.
  3. If there are any wrong fields, the error object is filled
  4. the error handling mode changes to “onChange”, meaning you’re now gonna be notified of every error change, even if you hadn’t hit submit

This is a great behavior and I wanna keep it, but the problem is, my error is defined in the “superRefine” method, and when this happens, it no longer updates dynamically (step 4 doesn’t work). I only see the error message change when I press submit again.

What I’m trying to achieve here, is to have a field required only if the contactType matches, so if contactType is email, require email, if contactType is userName, require userName. if I submit when email is empty (for example), it tells me “email is required”. but once I change contactType to userName, I want to see “userName” is required straight away.

How can I add a horizontall scroll to the top of an ag-grid?

I’ve tried previous solutions and it does not seem to be working. This is what I have so far but it doesn’t seem to be working. What can I add or modify?

< div id = “gridscrollsection” class = “orderbook-grid”>
<ng-container *ngIf =“showSummaryTab  === true">
    <ag-grid-angular domLayout='autoHeight' class =“ag-theme-balham ag-grid-width" [rowData] = “rowDataSummary"
        [defaultColDef] =“defaultColDef" [columnDefs] = “columnDefsTrancheSummary" [scrollbarWidth] = “8” [treeData] =“false"
        [animateRows] =“true" [gridOptions] =“gridoptions" [overlayNoRowsTemplate] = “gridOverlayTemplate"
        [excelStyles] = “excelstyles" [getContextMenuItems] = “getContextMenuItems" (gridReady) ="onGridReadySummary ($event)>
    </ag-grid-angular>
</ng-container>
</div>

::ng-deep  .orderbook-grid{
    .ag-root-wrapper-body{
    .ag-root{
        padding-top: 13px;
    }
    .ag-body-horizontal-scroll{
         position: absolute !important;
            
         top: 4px;
        webkit-overflow-scrolling: touch;
}
    .ag-center-cols-viewport{
        overflow-y: hidden; 
        overflow-x: hidden;
webkit-overflow-scrolling: touch;
}}}

:: .webkit-scrollbar {
    .webkit-appearance: none;
    .width: 8px; height: 8px;
    webkit-overflow-scrolling: touch;
}

:: -webkit-scrollbar-thumb {
    background-color: rgba(0,0,0,0.5) ; 
    border-radius: 4px; 
    box-shadow: 0 0 1px rgba (255, 255, 255, 0.5)

Difference between eventListener and event.targe on this question

Im trying to solve a simple problem in Js, where i need to rotate a string in js(only) on my html, but im facing problems with this two event handlers(im calling eventListener and event.target of event handlers because im not sure if they do the same thing or similar…).

Here is the html code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="Training">
        <meta name="author" content="Vitor Mota">
        <title>Training</title><!--Practice-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">                      
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="cssFile.css">
        <script src="JsExc.js" defer></script>
    </head>
    <body >

       
       <div class="Test_space" id="target">
        <button id="btnStart">Start</button>
          <div id="tt">w3resource</div> 
        <button id="btnStop">Stop</button>    
       </div>

        
       
        
    </body>
</html>

Here is my code in JS (whose not working when im using if(event.target == btnStop){ } and let btnStop= document.getElementById("btnStop");):

window.onclick = function(event){
    


    let Startbtn = document.getElementById("btnStart");
    let btnStop= document.getElementById("btnStop");

    let getId= document.getElementById("tt"); //Any id name
    let getSstringToReplace = getId.childNodes[0].data;


    let myInterval 
    

    if(event.target == btnStart){   
        myInterval = setInterval(start, 100);
    }

    if(event.target == btnStop){   
          clearInterval(myInterval);
    }

    function start(){   
        getSstringToReplace= getSstringToReplace[getSstringToReplace.length-1] + getSstringToReplace.substring(0, getSstringToReplace.length - 1);  
        
        getId.childNodes[0].data = getSstringToReplace;
    }
    
}

but when i change that part of the code if(event.target == btnStop){ } and let btnStop= document.getElementById("btnStop");
, and add a new function stop() and change my getelementbyid to addEventListener, like here:

window.onclick = function(event){
    


    let rodarbtn = document.getElementById("btnStart");
    document.getElementById("btnStop").addEventListener("click", stop);

    let getId= document.getElementById("tt");
    let getSstringToReplace = getId.childNodes[0].data;


    let myInterval 
    

    if(event.target == rodarbtn){   
        myInterval = setInterval(run, 100);
    }
    function stop(){
        clearInterval(myInterval);
    }
    function run(){   
        getSstringToReplace= getSstringToReplace[getSstringToReplace.length-1] + getSstringToReplace.substring(0, getSstringToReplace.length - 1);  
        
        getId.childNodes[0].data = getSstringToReplace;
    }
    
} 

this one work, someone can explain why?

Swagger cannot find user schema using Yaml files

Beginner here using swagger. I try to create a simple endpoint documentation. But I cannot figure what is wrong with my schema type.

I started by creating the folder structure: In my root src, I have the swagger config file in typescript format:

  • I referenced the API and Schame path using path module.
import swaggerJSDoc from "swagger-jsdoc";
import path from 'path';

const userSchemaPath = path.join(__dirname, 'middlewares', 'validators', 'userSignup.swagger.yaml');
const userRouter = path.join(__dirname, 'routes', 'user.swagger.yaml');


const options: swaggerJSDoc.Options = {
    definition: {
        openapi:    '3.0.0',
        info: {
            title:  'Chat app with Sockets.io and HTTP',
            version: '1.0',
            contact: {
                email: 'sasdansss***iel9@***.com',
                name: 'Daniel Mihai'
            }
        },
        servers: [
            {
                url: 'http://localhost:3001',
                description: 'Local env server. Localhsot...'
            }
        ]
    },

    //Array of API routes
    apis: [userRouter, userSchemaPath]
}


const swaggerSpec = swaggerJSDoc(options);
export default swaggerSpec;


enter image description here

Next, In the router I started to build the yaml for the router endpoints for users.

# User setup...
paths:
  /api/user:
    post:
      tags:
        - Users
      summary: Signup user. Create an account for the Chat application
      description: User is prompted to create an account for the application. User is required to use an unique email for the account.
      operationId: createUser
      requestBody:
        description: Fill all the fields and use a POST request /api/user to create a user.
        content: 
          application/json:
            schema: 
              $ref: '../middlewares/validators/userSignup.swagger.yaml'
            required: true
      responses:
        '201': 
          description: User created successfully
        '400':
          description: Invalid parameters provided. Zod validator responses
        '500':
          description: Something went wrong with the server. Or email duplicate error

Error here finding the schema…
I use morgan logger and get a 404 error for the reference schema… I dont understand whats wrong with it because I don’t get any syntax wrong. I checked also with ChatGPT and it points me to things that I already checked (check the path)…
::1 - - [06/Feb/2024:14:41:13 +0000] "GET /middlewares/validators/userSignup.swagger.yaml HTTP/1.1" 404 30

Next, I build the schema for the zod validator:

components:
  schemas:
    UserSchema:
      type: object
      properties:
        email:
          type: string
          description: Unique email required to create an account 
          example: [email protected]
        firstName:
          type: string
          description: first name 
          example: Daniel
        lastName:
          type: string
          description: last name 
          example: Michael
        password:
          type: string
          description: password will be hashed 
          example: MyPassword

Other localhsot swagger specs:
I don’t see the parameters:
enter image description here

I also don’t see the schema:
enter image description here

However, In the bottom of the screen page, the schema works:
enter image description here

Verify JWT token expiration in middleware of NextJS 14

I’m implementing an authentication & authorization app with JWT, NextJS & MongoDB

Here I can successfully do authentication like /signup & /signin. During /signin I’ve creating an JWT token & set it’s expires time for 1m (for testing)

  • Now After /signin I can visit /admin /profile & can fetch /profile data.
  • After 1m expires the /profile data can’t be fetched as expected

Problem

Although the token expires but still I can visit all route cause the token is already exist in cookies but not valid expire token.

  • I’ve create below middleware. Here if I try to

… && (!token || JSON.parse(token).expiredAt)

Here I’m getting

SyntaxError: Unexpected token ‘e’, “eyJhbGciOi”… is not valid JSON

And If I try to create a token verify function & call it to middleware than it show

Server Error: The edge runtime does not support Node.js ‘crypto’ module.

import { NextRequest, NextResponse } from "next/server";
import { isTokenExpires } from "./app/_utils/getDataOfToken";

export function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;
  const isAuth = ["/signin", "/signup"];
  const isProtected = ["/profile", "/admin", "/sales", "/cart"];

  const token = req.cookies.get("token")?.value;

  if (isProtected.includes(path) && (!token || isTokenExpires(token))) {
    const response = NextResponse.redirect(new URL("/signin", req.url));
    return response;
  }
}

export const config = {
  matcher: ["/", "/signup", "/signin", "/profile", "/admin", "/sales", "/cart"],
};

How can I verify the token in middleware?

How to shorten URLs client-side with JS? [closed]

I have a web app that stores its entire state as a base64 encoded query string in the URL (myapp.com?state=<long string>). This works well and does not need any backend, but the URL typically gets very long and it needs shortening in order to be practical and to be properly recognized as a proper URL by other programs.

I’m a aware of APIs such as Bitly and TinyURL, but I want to do the URL shortening in the browser and not rely on a backend or anyone else to remember links for me. How can I do that?

I’ve looked around the web and found little evidence of client-side URL shortening.