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

feat: query support array #25

Merged
merged 3 commits into from
Sep 12, 2024
Merged
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
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,21 @@ type LylaRequestOptions<C = undefined> = {
* `body`.
*/
json?: any
query?: Record<string, string | number>
/**
* Query object, also known as search params.
* Note, if you want to set `null` or `undefined` as value in query,
* use object like `query: { key: "undefined" }` instead of `query: { key: undefined }`.
* Otherwise, the k-v pair will be ignored.
*/
query?: Record<
string,
| string
| number
| boolean
| Array<string | number | boolean>
| null
| undefined
>
baseUrl?: string
/**
* Abort signal of the request.
Expand Down
16 changes: 15 additions & 1 deletion README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,21 @@ type LylaRequestOptions<C = undefined> = {
* 需要被写入请求主体的 JSON 值,不可以同时和 body 使用
*/
json?: any
query?: Record<string, string | number>
/**
* Query 对象,用于构建 URL 里的搜索参数 search params。
* 注意,如果你想在查询中设置 `null` 或 `undefined` 作为值,
* 请使用字符串作为值,如 `query: { key: "undefined" }` ,而非 `query: { key: undefined }`。
* 否则,该键值对将被忽略。
*/
query?: Record<
string,
| string
| number
| boolean
| Array<string | number | boolean>
| null
| undefined
>
baseUrl?: string
/**
* 请求使用的 Abort signal
Expand Down
24 changes: 17 additions & 7 deletions packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,15 @@ function isOkStatus(status: number): boolean {

declare const setTimeout: (callback: () => void, timeout?: number) => number

type URLSearchParamsLike = {
toString: () => string
append: (key: string, value: string) => void
}

// It exists both in node, browser, miniprogram environment
declare const URLSearchParams: {
new (params: Record<string, string>): { toString: () => string }
new (params: Record<string, string>): URLSearchParamsLike
new (): URLSearchParamsLike
}

export function createLyla<C, M extends LylaAdapterMeta>(
Expand Down Expand Up @@ -164,13 +170,17 @@ export function createLyla<C, M extends LylaAdapterMeta>(

// Resolve query string, patch it to URL
if (_options.query) {
const resolvedQuery: Record<string, string> = {}
for (const key in _options.query) {
const v = _options.query[key]
if (v === undefined || v === null) continue
resolvedQuery[key] = v.toString()
const urlSearchParams = new URLSearchParams()
for (const [key, value] of Object.entries(_options.query)) {
if (Array.isArray(value)) {
for (const v of value) {
urlSearchParams.append(key, v.toString())
}
} else if (value !== undefined && value !== null) {
urlSearchParams.append(key, value.toString())
}
}
const urlSearchParams = new URLSearchParams(resolvedQuery)

const queryString = urlSearchParams.toString()
if (_options.url.includes('?')) {
const badRequestError = defineLylaError<
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,15 @@ export type LylaRequestOptions<
* `body`.
*/
json?: any
query?: Record<string, string | number | boolean | undefined | null>
query?: Record<
string,
| string
| number
| boolean
| undefined
| null
| Array<string | number | boolean>
>
baseUrl?: string
/**
* Abort signal of the request.
Expand Down
5 changes: 5 additions & 0 deletions packages/test/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ func GetTestRoutes(r *gin.Engine) {
c.Header("X-UPPER", "X-UPPER")
c.Header("x-lower", "x-lower")
})
r.GET("/api/get-query", func(c *gin.Context) {
queryParams := c.Request.URL.Query()
// return {"key1": ["value1"]}
c.JSON(200, queryParams)
})
}

func PostTestRoutes(r *gin.Engine) {
Expand Down
38 changes: 37 additions & 1 deletion packages/test/tests/basic.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test } from '@playwright/test'
import { beforeEach } from './utils'
import "./types"
import './types'

beforeEach(test)
;(['get', 'post', 'delete', 'put', 'patch'] as const).forEach((method) => {
Expand Down Expand Up @@ -71,3 +71,39 @@ beforeEach(test)
})
}
})

test('parse normal query', async ({ page }) => {
const res = await page.evaluate(async () => {
const res = await window.lyla.get('/api/get-query', {
query: {
key1: 'value1'
}
})
return res.json
})
expect(res).toMatchObject({ key1: ['value1'] })
})

test('parse array query', async ({ page }) => {
const res = await page.evaluate(async () => {
const res = await window.lyla.get('/api/get-query', {
query: {
key1: ['value1', 'value2']
}
})
return res.json
})
expect(res).toMatchObject({ key1: ['value1', 'value2'] })
})

test('parse empty query', async ({ page }) => {
const res = await page.evaluate(async () => {
const res = await window.lyla.get('/api/get-query', {
query: {
key1: null
}
})
return res.json
})
expect(res).toMatchObject({})
})
Loading