Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 3, 2025 09:46
Show Gist options
  • Save yano3nora/ff76774845d42dc6f6d65107f489bb44 to your computer and use it in GitHub Desktop.
Save yano3nora/ff76774845d42dc6f6d65107f489bb44 to your computer and use it in GitHub Desktop.
sqids

Overview

https://sqids.org/javascript
https://github.com/sqids/sqids-javascript

数値の組み合わせから一意の識別子を生成し sns サービスの url みたいな運用するやつ。

$ npm i sqids

アルゴリズムの関係上 「適当に改ざんされた id から下の数値が decode されることがある」 ため、parse の際に id が正当なものであるかの検査は手動で行う必要がある

import Sqids from 'sqids'

export const ENCODER = new Sqids({ minLength: 16 })

export const getUrlId = (articleId, versionId) => {
  const params = [
    articleId,
    versionId,
  ]

  return ENCODER.encode(params) // 86Rf07xd4z890kdo
}

export const parseUrlId = (id: ReturnType<typeof getUrlId>[0]) => {
  const params = ENCODER.decode(id) // [1, 2]

  // verify valid of id
  if (id !== getUrlId(...params)) {
    return {}
  }

  return {
    articleId: params.at(0),
    versionId: params.at(1),
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment