splitbee / notion-api-worker

Notion as CMS with easy API access
MIT License
1.56k stars 197 forks source link

Feature request: normalize pageId before checking cache #12

Open transitive-bullshit opened 4 years ago

transitive-bullshit commented 4 years ago

Here's a function which extracts the pageId in a consistent format (no dashes) and ignores any additional prefix (like my-page-about-e5a735e33baa458b988993b55a54ee54):

const pageIdRe = /\b([a-f0-9]{32})$/
const pageId2Re = /\b([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/

/** Extracts the notion page ID from a notion URL suffix */
export const parsePageId = (id: string) => {
  id = id.split('?')[0]
  const match = id.match(pageIdRe)

  if (match) {
    return match[1]
  }

  const match2 = id.match(pageId2Re)
  if (match2) {
    return match2[1].replace(/-/g, '')
  }
}

And some ava unit tests that will probably be useful:

import test from 'ava'
import * as notion from './notion'

const pageIdFixturesSuccess = [
  '267c0d1f1df8457f9b5c8f7efca16d83',
  'Twitter-Automation-Tool-267c0d1f1df8457f9b5c8f7efca16d83',
  'www.notion.so/saasifysh/Twitter-Automation-Tool-267c0d1f1df8457f9b5c8f7efca16d83',
  'www.notion.so/saasifysh/Twitter-Automation-Tool-267c0d1f1df8457f9b5c8f7efca16d83?foo=bar&bar=foo',
  'https://www.notion.so/saasifysh/Standalone-Notion-Hosting-717a3608b1874cc5bafb5b9680b53395',
  'Standalone-Notion-Hosting-717a3608b1874cc5bafb5b9680b53395',
  'Standalone-Notion-Hosting-717a3608b1874cc5bafb5b9680b53395?foo',
  '-717a3608b1874cc5bafb5b9680b53395',
  '717a3608b1874cc5bafb5b9680b53395',
  '717a3608b1874cc5bafb5b9680b53395?',
  'e5a735e3-3baa-458b-9889-93b55a54ee54',
  'fde5ac74-eea3-4527-8f00-4482710e1af3',
  'about-e5a735e3-3baa-458b-9889-93b55a54ee54',
  '.com/about-e5a735e3-3baa-458b-9889-93b55a54ee54',
  'About-d9ae0c6e7cad49a78e21d240cf2e3d04'
]

const pageIdFixturesFailure = [
  '717A3608b1874CC5bafb5b9680b53395',
  '717A36',
  '',
  'notion.so/saasifysh/Twitter-Automation-Tool-267c0d1f1df8457f9b5c8f7efca16d83abc',
  'a267c0d1f1df8457f9b5c8f7efca16d83',
  '267c0d1f1df8457f9b5c8f7efca16d83a',
  '267c0d1f1%f8457f9b5c8f7efca16d83',
  'Twitter-Automation-Tool',
  'fde5ac74-eea3-4527-8f00-4482710e1af'
]

test('notion.parsePageId success', (t) => {
  for (const id of pageIdFixturesSuccess) {
    const parsedId = notion.parsePageId(id)
    t.truthy(parsedId)
    t.snapshot(parsedId)
  }
})

test('notion.parsePageId failure', (t) => {
  for (const id of pageIdFixturesFailure) {
    const parsedId = notion.parsePageId(id)
    t.falsy(parsedId)
  }
})