src/roblox/client.ts (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
import config from "@/config";
import type {
ApiError,
ApiErrorV2,
ErrorCode,
GatewayError,
GetUserResponse,
GetUsersByUsernamesPayload,
GetUsersByUsernamesResponse,
Result,
SearchUsersResponse,
UserRestrictionLog,
UserRestrictionLogsResponse,
} from "./types/";
const ERROR_CODES: Set<string> = new Set<ErrorCode>([
"INVALID_ARGUMENT",
"PERMISSION_DENIED",
"NOT_FOUND",
"ABORTED",
"RESOURCE_EXHAUSTED",
"CANCELLED",
"INTERNAL",
"NOT_IMPLEMENTED",
"UNAVAILABLE",
]);
function isErrorCode(value: string): value is ErrorCode {
return ERROR_CODES.has(value);
}
function isApiErrorV2(x: unknown): x is ApiErrorV2 {
return (
typeof x === "object" &&
x !== null &&
"code" in x &&
"message" in x &&
typeof (x as Record<string, unknown>).code === "string" &&
typeof (x as Record<string, unknown>).message === "string" &&
isErrorCode((x as Record<string, unknown>).code as string)
);
}
function isGatewayError(x: unknown): x is GatewayError {
return (
typeof x === "object" &&
x !== null &&
"errors" in x &&
Array.isArray((x as Record<string, unknown>).errors)
);
}
function isApiError(x: unknown): x is ApiError {
return isApiErrorV2(x) || isGatewayError(x);
}
function errorFromStatus(status: number, statusText: string): ApiErrorV2 {
const codeMap: Record<number, ErrorCode> = {
400: "INVALID_ARGUMENT",
403: "PERMISSION_DENIED",
404: "NOT_FOUND",
409: "ABORTED",
429: "RESOURCE_EXHAUSTED",
499: "CANCELLED",
500: "INTERNAL",
501: "NOT_IMPLEMENTED",
503: "UNAVAILABLE",
};
return {
code: codeMap[status] ?? "INTERNAL",
message: statusText,
};
}
class RobloxClient {
private readonly baseUrl = "https://apis.roblox.com";
private readonly cookie: string;
private readonly apiKey: string;
constructor(cookie: string, apiKey: string) {
this.cookie = cookie;
this.apiKey = apiKey;
}
async request<T>(path: string, init?: RequestInit): Promise<Result<T>> {
let baseUrl = this.baseUrl;
if (path.startsWith("https://")) {
baseUrl = "";
}
try {
const res = await fetch(`${baseUrl}${path}`, {
...init,
headers: {
Cookie: this.cookie,
"x-api-key": `${this.apiKey}`,
accept: "application/json",
"Content-Type": "application/json",
UserAgent:
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
...init?.headers,
},
});
const body = await res.json();
if (!res.ok || isApiError(body)) {
const err: ApiError = isApiError(body)
? body
: errorFromStatus(res.status, res.statusText);
console.log(res);
return [null, err];
}
return [body as T, null];
} catch (e) {
return [null, { code: "INTERNAL", message: String(e) }];
}
}
async getUserRestrictionLogs(
universeId: string,
userId: string,
): Promise<Result<UserRestrictionLog[]>> {
const allLogs: UserRestrictionLog[] = [];
let pageToken = "";
while (true) {
const filter = encodeURIComponent(
`place == '' && user == 'users/${userId}'`,
);
const path = `/user/cloud/v2/universes/${universeId}/user-restrictions:listLogs?filter=${filter}&pageToken=${pageToken}`;
const [data, err] = await this.request<UserRestrictionLogsResponse>(path);
if (err) return [null, err];
allLogs.push(...data.logs);
if (!data.nextPageToken) break;
pageToken = data.nextPageToken;
}
return [allLogs, null];
}
async getUser(userId: string): Promise<Result<GetUserResponse>> {
const path = `/cloud/v2/users/${userId}`;
const [data, err] = await this.request<GetUserResponse>(path);
if (err) return [null, err];
return [data, null];
}
async getUsersByUsernames(
usernames: string[],
): Promise<Result<GetUsersByUsernamesResponse>> {
const payload: GetUsersByUsernamesPayload = {
usernames,
excludeBannedUsers: false,
};
const path = "https://users.roblox.com/v1/usernames/users";
const [data, err] = await this.request<GetUsersByUsernamesResponse>(path, {
method: "POST",
body: JSON.stringify(payload),
});
if (err) return [null, err];
return [data, null];
}
async searchUsers(
keyword: string,
params: { limit: number; cursor: string } = { limit: 10, cursor: "" },
): Promise<Result<SearchUsersResponse>> {
const path = `https://users.roblox.com/v1/users/search?keyword=${encodeURIComponent(keyword)}&limit=${params.limit}&cursor=${params.cursor}`;
const [data, err] = await this.request<SearchUsersResponse>(path);
if (err) return [null, err];
return [data, null];
}
}
export const roblox = new RobloxClient(
config.roblox.cookie,
config.roblox.apiKey,
);
|