260 lines
10 KiB
TypeScript
260 lines
10 KiB
TypeScript
/**
|
|
* Common request-shape edge cases — catalogue §3.3 REQ-01..15.
|
|
*
|
|
* All calls go through the raw tRPC helpers so the wire shape (verb, batch body,
|
|
* extra fields) can be controlled precisely.
|
|
*/
|
|
|
|
import { rawMutation, rawQuery, uniqueSuffix } from '../helpers/api'
|
|
import { staffSession } from '../helpers/sessions'
|
|
import { COORDS, registerThrowawayUser } from '../helpers/fixtures'
|
|
import { TEST_REGION_ID } from '../helpers/env'
|
|
|
|
jest.setTimeout(180_000)
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Local response helpers */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
function batch0(body: unknown): any {
|
|
return Array.isArray(body) ? (body as any[])[0] : (body as any)
|
|
}
|
|
function codeOf(body: unknown): string | undefined {
|
|
return batch0(body)?.error?.data?.code
|
|
}
|
|
function httpStatusOf(body: unknown): number | undefined {
|
|
return batch0(body)?.error?.data?.httpStatus
|
|
}
|
|
function dataOf(body: unknown): any {
|
|
return batch0(body)?.result?.data
|
|
}
|
|
function errorMessageOf(body: unknown): string {
|
|
return String(batch0(body)?.error?.message ?? '')
|
|
}
|
|
|
|
describe('request shapes (§3.3)', () => {
|
|
it('REQ-01: an unknown procedure path is NOT_FOUND / 404', async () => {
|
|
const res = await rawQuery('nope.nope', {})
|
|
expect(httpStatusOf(res.body)).toBe(404)
|
|
expect(codeOf(res.body)).toBe('NOT_FOUND')
|
|
expect(errorMessageOf(res.body)).toMatch(/no procedure found/i)
|
|
})
|
|
|
|
it('REQ-02: the wrong HTTP verb is METHOD_NOT_SUPPORTED', async () => {
|
|
// GET on a mutation.
|
|
const getMutation = await rawQuery('user.auth.login', {
|
|
identifier: 'x@example.com',
|
|
password: 'y',
|
|
})
|
|
expect(codeOf(getMutation.body)).toBe('METHOD_NOT_SUPPORTED')
|
|
|
|
// POST on a query.
|
|
const postQuery = await rawMutation('common.healthCheck', {})
|
|
expect(codeOf(postQuery.body)).toBe('METHOD_NOT_SUPPORTED')
|
|
})
|
|
|
|
it('REQ-03: missing required input is BAD_REQUEST naming the field', async () => {
|
|
const user = await rawMutation('user.auth.register', { email: 'x@example.com' })
|
|
expect(codeOf(user.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(user.body)).toMatch(/password/)
|
|
|
|
const staff = await rawMutation('admin.staffUser.login', {})
|
|
expect(codeOf(staff.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(staff.body)).toMatch(/name/)
|
|
})
|
|
|
|
it('REQ-04: a wrong type (string where number) is BAD_REQUEST', async () => {
|
|
const staff = await staffSession()
|
|
const res = await rawQuery('admin.slots.getSlotById', { id: 'abc' }, { token: staff.token })
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(res.body)).toMatch(/id/)
|
|
expect(errorMessageOf(res.body)).toMatch(/expected number/i)
|
|
})
|
|
|
|
it('REQ-05: extra unknown fields are stripped, not written', async () => {
|
|
const suffix = uniqueSuffix()
|
|
const register = await rawMutation('user.auth.register', {
|
|
name: `Strip ${suffix}`,
|
|
email: `strip-${suffix}@example.com`,
|
|
mobile: `6${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
isAdmin: true,
|
|
role: 'superadmin',
|
|
})
|
|
const registeredUser = dataOf(register.body)?.data?.user
|
|
expect(registeredUser?.id).toEqual(expect.any(Number))
|
|
expect(registeredUser?.isAdmin).toBeUndefined()
|
|
expect(registeredUser?.role).toBeUndefined()
|
|
|
|
// The address schema strips `boundId`/`hostile`; the bound is derived from the
|
|
// coordinates instead (a client cannot smuggle in a foreign bound).
|
|
const token = dataOf(register.body)?.data?.token as string
|
|
const address = await rawMutation(
|
|
'user.address.createAddress',
|
|
{
|
|
regionId: TEST_REGION_ID,
|
|
name: 'Strip Address',
|
|
phone: '9876543210',
|
|
addressLine1: `1 Strip Rd ${suffix}`,
|
|
city: 'Mahabubnagar',
|
|
state: 'Telangana',
|
|
latitude: COORDS.region1Bound1.lat,
|
|
longitude: COORDS.region1Bound1.lng,
|
|
boundId: 3,
|
|
hostile: 'nope',
|
|
},
|
|
{ token }
|
|
)
|
|
const created = dataOf(address.body)?.data
|
|
expect(created?.id).toEqual(expect.any(Number))
|
|
expect(created?.boundId).toBe(1)
|
|
expect(created?.hostile).toBeUndefined()
|
|
})
|
|
|
|
it('REQ-06: null is accepted for nullable optionals and rejected for required fields', async () => {
|
|
const suffix = uniqueSuffix()
|
|
const optionalNull = await rawMutation('user.auth.register', {
|
|
name: `Null Optional ${suffix}`,
|
|
email: `null-optional-${suffix}@example.com`,
|
|
mobile: `7${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
profileImageUrl: null,
|
|
})
|
|
expect(codeOf(optionalNull.body)).toBeUndefined()
|
|
expect(dataOf(optionalNull.body)?.data?.user?.id).toEqual(expect.any(Number))
|
|
|
|
const requiredNull = await rawMutation('user.auth.register', {
|
|
name: null,
|
|
email: `null-required-${suffix}@example.com`,
|
|
mobile: `8${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
})
|
|
expect(codeOf(requiredNull.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(requiredNull.body)).toMatch(/name/)
|
|
})
|
|
|
|
it('REQ-07: a batch with one failing entry still returns the other result', async () => {
|
|
const res = await rawQuery('common.healthCheck,user.order.getOrders', { page: 1, pageSize: 1 })
|
|
const entries = res.body as any[]
|
|
expect(Array.isArray(entries)).toBe(true)
|
|
expect(entries).toHaveLength(2)
|
|
expect(entries[0].result.data.status).toBe('ok')
|
|
expect(entries[1].error.data.code).toBe('UNAUTHORIZED')
|
|
})
|
|
|
|
it('REQ-08: a too-large array is bounded by the schema', async () => {
|
|
const staff = await staffSession()
|
|
const tooMany = Array.from({ length: 51 }, (_, i) => i + 1)
|
|
const res = await rawMutation('admin.order.rebalanceSlots', { slotIds: tooMany }, { token: staff.token })
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(res.body)).toMatch(/too big|<=50/i)
|
|
})
|
|
|
|
it('REQ-09: a negative id is rejected where the schema declares positive', async () => {
|
|
const user = await registerThrowawayUser()
|
|
const res = await rawMutation('user.address.updateAddress', { id: -1 }, { token: user.token })
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(res.body)).toMatch(/id/)
|
|
})
|
|
|
|
it('REQ-10: a float where an int is expected is BAD_REQUEST', async () => {
|
|
const user = await registerThrowawayUser()
|
|
const res = await rawMutation('user.address.updateAddress', { id: 1.5 }, { token: user.token })
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(res.body)).toMatch(/int/i)
|
|
expect(errorMessageOf(res.body)).toMatch(/id/)
|
|
})
|
|
|
|
it('REQ-11: an empty string in a required field is BAD_REQUEST', async () => {
|
|
const suffix = uniqueSuffix()
|
|
const res = await rawMutation('user.auth.register', {
|
|
name: '',
|
|
email: `empty-name-${suffix}@example.com`,
|
|
mobile: `9${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
})
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST')
|
|
expect(errorMessageOf(res.body)).toMatch(/name is required/i)
|
|
})
|
|
|
|
it('REQ-12: SQL-like search strings are treated as text', async () => {
|
|
const staff = await staffSession()
|
|
const res = await rawQuery(
|
|
'admin.user.getAllUsers',
|
|
{ limit: 5, search: "' OR 1=1 --" },
|
|
{ token: staff.token }
|
|
)
|
|
expect(codeOf(res.body)).toBeUndefined()
|
|
expect(Array.isArray(dataOf(res.body)?.users)).toBe(true)
|
|
|
|
const dropped = await rawQuery(
|
|
'admin.user.getAllUsers',
|
|
{ limit: 5, search: "x'; DROP TABLE users; --" },
|
|
{ token: staff.token }
|
|
)
|
|
expect(codeOf(dropped.body)).toBeUndefined()
|
|
expect(Array.isArray(dataOf(dropped.body)?.users)).toBe(true)
|
|
})
|
|
|
|
it('REQ-13: Unicode/emoji names are stored and returned unchanged', async () => {
|
|
const staff = await staffSession()
|
|
const name = `🐔 Emoji Store ✅ ${uniqueSuffix()}`
|
|
const res = await rawMutation(
|
|
'admin.store.createStore',
|
|
{ name, description: 'emoji round-trip' },
|
|
{ token: staff.token }
|
|
)
|
|
expect(codeOf(res.body)).toBeUndefined()
|
|
const store = dataOf(res.body)?.store
|
|
expect(store?.id).toBeGreaterThan(0)
|
|
expect(store?.name).toBe(name)
|
|
})
|
|
|
|
it('REQ-14: whitespace is trimmed per procedure (register trims name, lowercases email)', async () => {
|
|
const suffix = uniqueSuffix()
|
|
const res = await rawMutation('user.auth.register', {
|
|
name: ' Padded Name ',
|
|
email: ` PADDED-${suffix}@Example.COM `,
|
|
mobile: `6${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
})
|
|
// The email zod rule rejects surrounding whitespace outright, so trim it on
|
|
// the way in and assert the lowercase/trim the handler applies.
|
|
const cleanEmail = `PADDED-${suffix}@Example.COM`
|
|
const retry = await rawMutation('user.auth.register', {
|
|
name: ' Padded Name ',
|
|
email: cleanEmail,
|
|
mobile: `6${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`,
|
|
password: 'FreshyoTest!2026',
|
|
})
|
|
expect(codeOf(res.body)).toBe('BAD_REQUEST') // whitespace-padded email
|
|
expect(codeOf(retry.body)).toBeUndefined()
|
|
const user = dataOf(retry.body)?.data?.user
|
|
expect(user?.name).toBe('Padded Name')
|
|
expect(user?.email).toBe(cleanEmail.toLowerCase())
|
|
})
|
|
|
|
it('(current) REQ-15: concurrent identical mutations never surface a raw unique-key crash', async () => {
|
|
const staff = await staffSession()
|
|
const couponCode = `RACE${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`
|
|
const payload = { couponCode, flatDiscount: 10, isApplyForAll: true }
|
|
|
|
const [a, b] = await Promise.all([
|
|
rawMutation('admin.coupon.create', payload, { token: staff.token }),
|
|
rawMutation('admin.coupon.create', payload, { token: staff.token }),
|
|
])
|
|
|
|
const codes = [codeOf(a.body), codeOf(b.body)]
|
|
// At least one request must win.
|
|
expect(codes.filter((code) => code === undefined).length).toBeGreaterThanOrEqual(1)
|
|
for (const code of codes) {
|
|
if (code !== undefined) {
|
|
// (current) the duplicate path is a check-then-insert that throws a plain
|
|
// Error -> INTERNAL_SERVER_ERROR ("Coupon code already exists"), not 409.
|
|
expect(['CONFLICT', 'INTERNAL_SERVER_ERROR']).toContain(code)
|
|
}
|
|
}
|
|
// Whichever way the race resolves, no raw D1/SQL error reaches the client.
|
|
expect(`${a.text}\n${b.text}`).not.toMatch(/SQLITE_CONSTRAINT|UNIQUE constraint failed|D1_ERROR/i)
|
|
})
|
|
})
|