ecyrbe / zodios

typescript http client and server with zod validation
https://www.zodios.org/
MIT License
1.71k stars 46 forks source link

headers object doesn't accept the defined schema #141

Closed thelinuxlich closed 2 years ago

thelinuxlich commented 2 years ago

I have a parameter with the Header type defined as:

{
  type: 'Header',
  name: 'token',
  schema: z.object({
    Authorization: z.string().transform(s => {
      return `Basic ${Buffer.from(s + ':').toString('base64')}`
    }),
  }),
}

But when I try to use it like this:

zoop.getMarketplaceTransactions({
  params: { id: marketplace_id },
  headers: {
    token: {
      Authorization: key,
    },
  },
})

The typechecker complains about the object shape: image

thelinuxlich commented 2 years ago

Changing the schema to z.string() instead of z.object() solved it

ecyrbe commented 2 years ago

yes, use a string schema.

But i'll recommend using axios auth parameter or use plugin token to inject auth headers cf : https://www.zodios.org/docs/client/plugins#authorization-with-token-plugin or axios auth https://www.zodios.org/docs/client#request-options

ecyrbe commented 2 years ago

if you want to send manually anyway here the correct setup

{
  type: 'Header',
  name: 'Authorization',
  schema: z.string().transform(s => {
      return `Basic ${Buffer.from(s + ':').toString('base64')}`
    }),
}
thelinuxlich commented 2 years ago

I'm declaring like that because I don't want auth to be optional

ecyrbe commented 2 years ago

i see.
if you are using basic auth for each endpoint, i could create a basic auth plugin that you could use without needed to require you to pass it manually for each call.
like this :

client.use(pluginBasicAuth(() => {
   return { username: 'my user', password: 'my password' }
 }));

and now it will be injected in all your calls

if you are interested in this. feel free to create a plugin request. since token plugin is dedicated to do the same but for bearer token that are more common in APIs