Liliana797979

request validator - js advanced

Oct 5th, 2021
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.      
  3. function fn(obj) {
  4.     const validMethods = ["GET", "POST", "DELETE", "CONNECT"];
  5.     const validVersions = ["HTTP/0.9", "HTTP/1.0" ,"HTTP/1.1", "HTTP/2.0"];
  6.     const uriRegex = /(^[\w.]+$)/;
  7.     const messageTest = /([<>\\&'"])/;
  8.  
  9.  
  10.     if (!obj.method || !validMethods.includes(obj.method)) {
  11.         throw new Error(`Invalid request header: Invalid Method`);
  12.     }
  13.  
  14.     if (!obj.uri || obj.uri == "" || !uriRegex.test(obj.uri)) {
  15.         throw new Error(`Invalid request header: Invalid URI`)
  16.     }
  17.  
  18.     if (!obj.version || !validVersions.includes(obj.version)) {
  19.         throw new Error("Invalid request header: Invalid Version")
  20.     }
  21.  
  22.     if (obj.message == undefined || messageTest.test(obj.message)) {
  23.         throw new Error("Invalid request header: Invalid Message");
  24.     }
  25.  
  26.  
  27.     return obj;
  28. }
  29.  
  30. // module.exports = {fn};
  31.  
  32. console.log(fn({
  33.   method: 'GET',
  34.   uri: 'svn.public.catalog',
  35.   version: 'HTTP/1.1',
  36. }))
Advertisement
Add Comment
Please, Sign In to add comment