Advertisement
WalshyDev

Paste Service - Cloudflare Workers

Mar 21st, 2021 (edited)
985
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  2. const url = 'https://cf-paste.walshy.dev/';
  3.  
  4. addEventListener('fetch', event => {
  5.   try {
  6.     event.respondWith(handleRequest(event.request))
  7.   } catch (e) {
  8.     return new Response(JSON.stringify(e), { 'Content-Type': 'application/json' });
  9.   }
  10. })
  11.  
  12. async function handleRequest(request) {
  13.   const { pathname } = new URL(request.url);
  14.  
  15.   if (pathname === '' || pathname === '/') {
  16.     return new Response('Send a POST to /documents in order to paste!');
  17.   } else if (pathname === '/documents' && request.method === 'POST') {
  18.     const content = await request.text();
  19.  
  20.     if (content.trim().length === 0) {
  21.       return new Response('{"error": "Please provide a body!"}', { 'Content-Type': 'application/json' });
  22.     }
  23.  
  24.     const id = getRandomString();
  25.  
  26.     await KV.put(id, content, { expirationTtl: 86400 });
  27.  
  28.     return new Response(JSON.stringify({
  29.       key: id, url: url + id,
  30.       note: 'It may take up to 60 seconds for the paste to become available!'
  31.     }), { 'Content-Type': 'application/json'});
  32.   } else {
  33.     const data = await KV.get(pathname.substring(1));
  34.  
  35.     if (data === null) {
  36.       return new Response('Not found!', { status: 404 });
  37.     } else {
  38.       return new Response(data);
  39.     }
  40.   }
  41.  
  42.   function getRandomString() {
  43.     // Pick characers randomly
  44.     let str = '';
  45.     for (let i = 0; i < 12; i++) {
  46.         str += chars.charAt(Math.floor(Math.random() * chars.length));
  47.     }
  48.  
  49.     return str;
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement