Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for parsing arrays into base64 strings in the URL. #552

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ import {
parseAsTimestamp,
parseAsIsoDateTime,
parseAsArrayOf,
parseAsBase64ArrayOf,
parseAsJson,
parseAsStringEnum,
parseAsStringLiteral,
Expand All @@ -115,6 +116,7 @@ useQueryState('darkMode', parseAsBoolean)
useQueryState('after', parseAsTimestamp) // state is a Date
useQueryState('date', parseAsIsoDateTime) // state is a Date
useQueryState('array', parseAsArrayOf(parseAsInteger)) // state is number[]
useQueryState('base64', parseAsBase64ArrayOf(parseAsJson)) // state is an object[]
useQueryState('json', parseAsJson<Point>()) // state is a Point

// Enums (string-based only)
Expand Down
15 changes: 15 additions & 0 deletions packages/nuqs/src/parsers.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { describe, expect, test } from 'vitest'
import {
parseAsArrayOf,
parseAsBase64ArrayOf,
parseAsFloat,
parseAsHex,
parseAsInteger,
parseAsIsoDateTime,
parseAsJson,
parseAsString,
parseAsTimestamp
} from './parsers'
Expand Down Expand Up @@ -55,6 +57,19 @@ describe('parsers', () => {
expect(parser.serialize(['a', ',', 'b'])).toBe('a,%2C,b')
})

test('parseAsBase64ArrayOf', () => {
const stringParser = parseAsBase64ArrayOf(parseAsString)
expect(stringParser.serialize([])).toBe('')
expect(stringParser.serialize(['a', ',', 'b'])).toBe('WyJhIiwiLCIsImIiXQ==')

const objectParser =
parseAsBase64ArrayOf(parseAsJson<{ a?: number; b?: number }>())

expect(objectParser.serialize([{ a: 1 }, { b: 2 }])).toBe(
'WyJ7XCJhXCI6MX0iLCJ7XCJiXCI6Mn0iXQ=='
)
})

test('parseServerSide with default (#384)', () => {
const p = parseAsString.withDefault('default')
const searchParams = {
Expand Down
49 changes: 49 additions & 0 deletions packages/nuqs/src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,3 +404,52 @@ export function parseAsArrayOf<ItemType>(
}
})
}

/**
* Encode an array of items into a base64 string in the querystring.
* Items are JSON-encoded before being base64-encoded.
*
* @param itemParser Parser for each individual item in the array
* @returns A parser that can be used with `useQueryState`
*/
export function parseAsBase64ArrayOf<ItemType>(itemParser: Parser<ItemType>) {
return createParser<ItemType[]>({
parse: query => {
if (!query) return null
if (query === '') return []
try {
const decoded = Buffer.from(query, 'base64').toString('utf-8')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Buffer is a Node.js API, and this code needs to run both on the server and in browsers. atob is not recommended either as it doesn't support Unicode text inputs, though there are workarounds. There is a proposal for browser-native base64 encoding, but it's still in early stages.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would love to implement a more generic approach. Do you have any ideas or opinions on what using it would look like?

re unicode-safe implementation: I can't find a good wrapper what would fit the bill, so I'll probably look into the workarounds you linked to.

Copy link
Member

@franky47 franky47 May 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An example would be (using only atob/btoa for simplicity):

export function parseAsBase64<T>(parser: Parser<T>) {
  return createParser<T>({
    parse: query => {
      if (!query) return null
      try {
        return parser.parse(atob(query))
      } catch {
        return null
      }
    },
    serialize: value => btoa((parser.serialize ?? String)(value))
  })
}

const parsed = JSON.parse(decoded)

if (!Array.isArray(parsed)) {
return null
}
return parsed
.map(item => itemParser.parse(item))
.filter(item => item !== null) as ItemType[]
} catch {
return null
}
},
serialize: values => {
if (values.length === 0) {
return ''
}
const serialized = values.map(item =>
itemParser.serialize ? itemParser.serialize(item) : item
)
const stringified = JSON.stringify(serialized)
const encoded = Buffer.from(stringified).toString('base64')
return encoded
},
eq(a, b) {
if (a === b) {
return true // Referentially stable
}
if (a.length !== b.length) {
return false
}
return a.every((value, index) => itemParser.eq!(value, b[index]!))
}
})
}
Loading