Skip to content

Commit

Permalink
chore: add usage without gramio in files
Browse files Browse the repository at this point in the history
  • Loading branch information
kravetsone committed Feb 7, 2024
1 parent 2e2da4c commit 710051c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export default defineConfig({
},
{ text: "Media Upload", link: "/files/media-upload" },
{ text: "Media Input", link: "/files/media-input" },
{
text: "Usage without GramIO",
link: "/files/usage-without-gramio",
},
],
},
{ text: "Types", link: "/types/index.html" },
Expand Down
47 changes: 47 additions & 0 deletions docs/files/usage-without-gramio.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Usage without GramIO

## Write you own type-safe TBA API wrapper with File uploading support!

```ts
import type { ApiMethods, TelegramAPIResponse } from "@gramio/types";
import { isMediaUpload, convertJsonToFormData } from "@gramio/files";
import { FormDataEncoder } from "form-data-encoder";

const TBA_BASE_URL = "https://api.telegram.org/bot";
const TOKEN = "";

const api = new Proxy({} as ApiMethods, {
get:
<T extends keyof ApiMethods>(_target: ApiMethods, method: T) =>
(params: Parameters<ApiMethods[T]>[0]) => {
const reqOptions: RequestInit = {
method: "POST",
duplex: "half",
};

if (isMediaUpload(method, params)) {
const formData = await convertJsonToFormData(method, params);

const encoder = new FormDataEncoder(formData);

reqOptions.body = encoder.encode();
reqOptions.headers = encoder.headers;
} else {
reqOptions.headers = {
"Content-Type": "application/json",
};
reqOptions.body = JSON.stringify(params);
}

const response = await fetch(
`${TBA_BASE_URL}${TOKEN}/${method}`,
reqOptions
);

const data = (await response.json()) as TelegramAPIResponse;
if (!data.ok) throw new APIError({ method, params }, data);

return data.result;
},
});
```

0 comments on commit 710051c

Please sign in to comment.