Skip to content

Commit 16cad09

Browse files
authored
Fetch API (#375)
* Create index.js * Core File * Docs Readme for Know * Core FILE
1 parent a19a98e commit 16cad09

File tree

2 files changed

+177
-0
lines changed

2 files changed

+177
-0
lines changed

scripts/fetch-api/README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Fetch
2+
3+
## Description
4+
5+
The `Fetch` class simplifies HTTP requests in Minecraft Bedrock Edition. It supports common HTTP methods like `GET`, `POST`, `PUT`, and `DELETE`, and automatically handles JSON data.
6+
7+
### Methods
8+
9+
#### `constructor(baseURL: string)`
10+
- Initializes a new `Fetch` instance with the specified base URL.
11+
12+
#### `get(path: string, params?: Object): Promise<Object>`
13+
- Sends an HTTP `GET` request to the specified path with optional query parameters.
14+
15+
#### `post(path: string, data: Object): Promise<Object>`
16+
- Sends an HTTP `POST` request to the specified path with the provided data.
17+
18+
#### `put(path: string, data: Object): Promise<Object>`
19+
- Sends an HTTP `PUT` request to the specified path with the provided data.
20+
21+
#### `delete(path: string): Promise<Object>`
22+
- Sends an HTTP `DELETE` request to the specified path.
23+
24+
### Example
25+
```js
26+
import { Fetch } from './fetch.js';
27+
28+
// Initialize Fetch instance
29+
const api = new Fetch("https://jsonplaceholder.typicode.com");
30+
31+
// GET example
32+
api.get("/posts", { userId: 1 }).then((data) => console.log(data));
33+
34+
// POST example
35+
api.post("/posts", {
36+
title: "foo",
37+
body: "bar",
38+
userId: 1
39+
}).then((data) => console.log(data));
40+
41+
// PUT example
42+
api.put("/posts/1", {
43+
title: "updated title",
44+
body: "updated body",
45+
userId: 1
46+
}).then((data) => console.log(data));
47+
48+
// DELETE example
49+
api.delete("/posts/1").then((data) => console.log(data));
50+
```
51+
52+
## Credits
53+
54+
These scripts were written by [nperma](https://github.com/nperma)

scripts/fetch-api/index.js

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Script example for ScriptAPI
2+
// Author: nperma <https://github.com/nperma>
3+
// Project: https://github.com/JaylyDev/ScriptAPI
4+
5+
import {
6+
http,
7+
HttpHeader,
8+
HttpRequest,
9+
HttpRequestMethod,
10+
} from "@minecraft/server-net";
11+
12+
/**
13+
* Class Fetch - Abstraction for HTTP Requests
14+
*/
15+
class Fetch {
16+
/**
17+
* Constructor to initialize the base URL.
18+
* @param {string} baseURL - The base URL for API requests.
19+
*/
20+
constructor(baseURL) {
21+
this.baseURL = baseURL.trim();
22+
}
23+
24+
/**
25+
* Performs an HTTP GET request.
26+
* @param {string} path - The API endpoint path.
27+
* @param {Object} [params={}] - Query parameters.
28+
* @returns {Promise<Object>} - The response body as JSON.
29+
*/
30+
async get(path, params = {}) {
31+
const queryString = this._buildQueryString(params);
32+
const uri = `${this.baseURL}${path}${queryString}`;
33+
const request = new HttpRequest(uri);
34+
request.method = HttpRequestMethod.Get;
35+
request.headers = [new HttpHeader("Content-Type", "application/json")];
36+
37+
const response = await http.request(request);
38+
return this._handleResponse(response);
39+
}
40+
41+
/**
42+
* Performs an HTTP POST request.
43+
* @param {string} path - The API endpoint path.
44+
* @param {Object} data - The data to send in the request body.
45+
* @returns {Promise<Object>} - The response body as JSON.
46+
*/
47+
async post(path, data) {
48+
const uri = `${this.baseURL}${path}`;
49+
const request = new HttpRequest(uri);
50+
request.method = HttpRequestMethod.Post;
51+
request.body = JSON.stringify(data);
52+
request.headers = [new HttpHeader("Content-Type", "application/json")];
53+
54+
const response = await http.request(request);
55+
return this._handleResponse(response);
56+
}
57+
58+
/**
59+
* Performs an HTTP PUT request.
60+
* @param {string} path - The API endpoint path.
61+
* @param {Object} data - The data to send in the request body.
62+
* @returns {Promise<Object>} - The response body as JSON.
63+
*/
64+
async put(path, data) {
65+
const uri = `${this.baseURL}${path}`;
66+
const request = new HttpRequest(uri);
67+
request.method = HttpRequestMethod.Put;
68+
request.body = JSON.stringify(data);
69+
request.headers = [new HttpHeader("Content-Type", "application/json")];
70+
71+
const response = await http.request(request);
72+
return this._handleResponse(response);
73+
}
74+
75+
/**
76+
* Performs an HTTP DELETE request.
77+
* @param {string} path - The API endpoint path.
78+
* @returns {Promise<Object>} - The response body as JSON.
79+
*/
80+
async delete(path) {
81+
const uri = `${this.baseURL}${path}`;
82+
const request = new HttpRequest(uri);
83+
request.method = HttpRequestMethod.Delete;
84+
request.headers = [new HttpHeader("Content-Type", "application/json")];
85+
86+
const response = await http.request(request);
87+
return this._handleResponse(response);
88+
}
89+
90+
/**
91+
* Handles the response from the server.
92+
* @param {Object} response - The HTTP response object.
93+
* @returns {Promise<Object>} - The parsed JSON body.
94+
* @throws {Error} - If the response status is not 200.
95+
*/
96+
async _handleResponse(response) {
97+
if (response.status !== 200) {
98+
throw new Error(
99+
`HTTP Error: ${response.status} - ${response.body}`
100+
);
101+
}
102+
return JSON.parse(response.body);
103+
}
104+
105+
/**
106+
* Builds a query string from an object of parameters.
107+
* @param {Object} params - The query parameters.
108+
* @returns {string} - The query string.
109+
*/
110+
_buildQueryString(params) {
111+
const entries = Object.entries(params);
112+
if (entries.length === 0) return "";
113+
return (
114+
"?" +
115+
entries
116+
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
117+
.join("&")
118+
);
119+
}
120+
}
121+
122+
export { Fetch };
123+

0 commit comments

Comments
 (0)