handler.ts 924 B

12345678910111213141516171819202122232425
  1. const CRAWLER_USER_AGENT_REGEX =
  2. /googlebot|YandexBot|baiduspider|twitterbot|facebookexternalhit|discordbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|Rocket.Chat|Minds|Taringa|redditbot/i
  3. declare global {
  4. const ATLAS_URL: string
  5. const META_SERVER_URL: string
  6. }
  7. function joinUrlFragments(...fragments: string[]) {
  8. const strippedFragments = fragments.map((f) => f.replace(/^\/|\/$/, ''))
  9. return strippedFragments.join('/')
  10. }
  11. export async function handleRequest(request: Request): Promise<Response> {
  12. const { pathname } = new URL(request.url)
  13. const userAgent = request.headers.get('User-Agent')
  14. if (userAgent?.match(CRAWLER_USER_AGENT_REGEX)) {
  15. const metaServerPath = joinUrlFragments(META_SERVER_URL, pathname)
  16. return fetch(metaServerPath)
  17. }
  18. const atlasPath = joinUrlFragments(ATLAS_URL, pathname)
  19. return fetch(atlasPath)
  20. }