MCPcopy Index your code
hub / github.com/4ian/GDevelop / fetchAsPlayer

Function fetchAsPlayer

Extensions/Multiplayer/multiplayertools.ts:56–109  ·  view source on GitHub ↗
({
    relativeUrl,
    method,
    body,
    dev,
  }: {
    relativeUrl: string;
    method: 'GET' | 'POST';
    body?: string;
    dev: boolean;
  })

Source from the content-addressed store, hash-verified

54 : Date.now;
55
56 const fetchAsPlayer = async ({
57 relativeUrl,
58 method,
59 body,
60 dev,
61 }: {
62 relativeUrl: string;
63 method: 'GET' | 'POST';
64 body?: string;
65 dev: boolean;
66 }) => {
67 const playerId = gdjs.playerAuthentication.getUserId();
68 const playerToken = gdjs.playerAuthentication.getUserToken();
69 if (!playerId || !playerToken) {
70 logger.warn('Cannot fetch as a player if the player is not connected.');
71 throw new Error(
72 'Cannot fetch as a player if the player is not connected.'
73 );
74 }
75
76 const rootApi = dev
77 ? 'https://api-dev.gdevelop.io'
78 : 'https://api.gdevelop.io';
79 const url = new URL(`${rootApi}${relativeUrl}`);
80 url.searchParams.set('playerId', playerId);
81 const formattedUrl = url.toString();
82
83 const headers = {
84 'Content-Type': 'application/json',
85 Authorization: `player-game-token ${playerToken}`,
86 };
87 const response = await fetch(formattedUrl, {
88 method,
89 headers,
90 body,
91 });
92 if (!response.ok) {
93 throw new Error(
94 `Error while fetching as a player: ${response.status} ${response.statusText}`
95 );
96 }
97
98 // Response can either be 'OK' or a JSON object. Get the content before trying to parse it.
99 const responseText = await response.text();
100 if (responseText === 'OK') {
101 return;
102 }
103
104 try {
105 return JSON.parse(responseText);
106 } catch (error) {
107 throw new Error(`Error while parsing the response: ${error}`);
108 }
109 };
110
111 /**
112 * @category Multiplayer

Callers 6

sendHeartbeatToBackendFunction · 0.85
handleHostDisconnectedFunction · 0.85
endLobbyGameFunction · 0.85
quickJoinLobbyFunction · 0.85
quickJoinWithLobbyIDFunction · 0.85

Calls 5

setMethod · 0.65
toStringMethod · 0.65
warnMethod · 0.45
textMethod · 0.45
parseMethod · 0.45

Tested by

no test coverage detected