Skip to content

Commit 3654178

Browse files
committed
Add nice scripts to query the Torii GrahpQL API
1 parent 964e5da commit 3654178

File tree

4 files changed

+350
-50
lines changed

4 files changed

+350
-50
lines changed

‎.gitignore‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
archived-unity-game/
22
references/
3-
4-
# Unity generated directories
5-
/[Ll]ibrary/
6-
/[Tt]emp/
7-
/[Oo]bj/
8-
/[Bb]uild/
9-
/[Bb]uilds/
10-
/[Ll]ogs/
11-
/[Uu]ser[Ss]ettings/
3+
# Unity generated directories in the unity-game subdirectory
4+
unity-game/[Ll]ibrary/
5+
unity-game/[Tt]emp/
6+
unity-game/[Oo]bj/
7+
unity-game/[Bb]uild/
8+
unity-game/[Bb]uilds/
9+
unity-game/[Ll]ogs/
10+
unity-game/[Uu]ser[Ss]ettings/
1211

1312
# Unity3D generated meta files
1413
*.pidb.meta

‎scripts/copy_dojo_files.sh‎

Lines changed: 0 additions & 41 deletions
This file was deleted.

‎scripts/game_sessions.js‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* Game Session Time Converter
5+
*
6+
* This script fetches game sessions from the GraphQL endpoint and converts timestamp values
7+
* to human-readable dates. It doesn't require any external dependencies.
8+
*/
9+
10+
// Function to convert hex string timestamp to human readable date
11+
function hexToDate(hexTimestamp) {
12+
if (!hexTimestamp) return { error: 'Missing timestamp' };
13+
14+
// Remove '0x' prefix if present and convert to decimal
15+
const decimal = parseInt(hexTimestamp.replace(/^0x/, ''), 16);
16+
17+
// Create a date object from the Unix timestamp (seconds)
18+
const date = new Date(decimal * 1000);
19+
20+
// Format the date in a readable way
21+
return {
22+
unixTimestamp: decimal,
23+
iso: date.toISOString(),
24+
localTime: date.toLocaleString(),
25+
relative: getRelativeTimeString(date)
26+
};
27+
}
28+
29+
// Helper to show a relative time string like "2 minutes ago"
30+
function getRelativeTimeString(date) {
31+
const now = new Date();
32+
const diffSeconds = Math.floor((now - date) / 1000);
33+
34+
if (diffSeconds < 0) return 'in the future';
35+
if (diffSeconds < 60) return `${diffSeconds} seconds ago`;
36+
if (diffSeconds < 3600) return `${Math.floor(diffSeconds/60)} minutes ago`;
37+
if (diffSeconds < 86400) return `${Math.floor(diffSeconds/3600)} hours ago`;
38+
return `${Math.floor(diffSeconds/86400)} days ago`;
39+
}
40+
41+
// Format session duration in a human-friendly way
42+
function formatDuration(seconds) {
43+
if (seconds < 60) return `${seconds} seconds`;
44+
if (seconds < 3600) return `${Math.floor(seconds/60)} minutes ${seconds%60} seconds`;
45+
const hours = Math.floor(seconds/3600);
46+
const minutes = Math.floor((seconds%3600)/60);
47+
return `${hours} hours ${minutes} minutes`;
48+
}
49+
50+
// Function to fetch game sessions from GraphQL endpoint
51+
async function fetchGameSessions() {
52+
const graphqlEndpoint = 'http://0.0.0.0:8080/graphql';
53+
const query = `
54+
query GetGameSessions {
55+
entities(keys: ["*"], first: 10) {
56+
edges {
57+
node {
58+
keys
59+
models {
60+
... on dojo_starter_GameSession {
61+
player
62+
start_time
63+
remaining_time
64+
active
65+
score
66+
last_update
67+
}
68+
}
69+
}
70+
}
71+
}
72+
}
73+
`;
74+
75+
try {
76+
const response = await fetch(graphqlEndpoint, {
77+
method: 'POST',
78+
headers: {
79+
'Content-Type': 'application/json',
80+
'Accept': 'application/json'
81+
},
82+
body: JSON.stringify({ query })
83+
});
84+
85+
if (!response.ok) {
86+
throw new Error(`HTTP error! Status: ${response.status}`);
87+
}
88+
89+
const data = await response.json();
90+
return data;
91+
} catch (error) {
92+
console.error('Failed to fetch data:', error);
93+
return null;
94+
}
95+
}
96+
97+
// Process and display game sessions
98+
async function processGameSessions() {
99+
console.log('Fetching game sessions from GraphQL endpoint...');
100+
const data = await fetchGameSessions();
101+
102+
if (!data || !data.data) {
103+
console.log('No data received or server is not reachable. Using sample data instead...');
104+
// Use sample data as fallback
105+
processSampleData();
106+
return;
107+
}
108+
109+
const edges = data.data.entities.edges;
110+
console.log(`\nFound ${edges.length} game sessions:\n`);
111+
112+
edges.forEach((edge, index) => {
113+
// The game session appears to be in the second item of the models array (index 1)
114+
// and doesn't have a __typename property
115+
const session = edge.node.models[1];
116+
if (!session || !session.player) return;
117+
118+
console.log(`\n==== Game Session ${index + 1} ====`);
119+
console.log(`Player: ${session.player}`);
120+
console.log('Score:', session.score);
121+
console.log('Active:', session.active);
122+
123+
// Process time data
124+
const startTime = hexToDate(session.start_time);
125+
const lastUpdate = hexToDate(session.last_update);
126+
127+
console.log('\nStart time:', startTime.localTime, `(${startTime.relative})`);
128+
console.log('Last update:', lastUpdate.localTime, `(${lastUpdate.relative})`);
129+
130+
// Calculate session duration
131+
if (session.start_time && session.last_update) {
132+
const startTimestamp = parseInt(session.start_time.replace(/^0x/, ''), 16);
133+
const lastUpdateTimestamp = parseInt(session.last_update.replace(/^0x/, ''), 16);
134+
const duration = lastUpdateTimestamp - startTimestamp;
135+
console.log('Session duration:', formatDuration(duration));
136+
}
137+
138+
console.log('====================');
139+
});
140+
}
141+
142+
// Process sample data if GraphQL endpoint is not available
143+
function processSampleData() {
144+
const gameSession = {
145+
"player": "0x127fd5f1fe78a71f8bcd1fec63e3fe2f0486b6ecd5c86a0466c3a21fa5cfcec",
146+
"start_time": "0x68516b39",
147+
"remaining_time": 0,
148+
"active": true,
149+
"score": 9,
150+
"last_update": "0x68516b56"
151+
};
152+
153+
console.log('\n==== Sample Game Session ====');
154+
console.log(`Player: ${gameSession.player}`);
155+
console.log('Score:', gameSession.score);
156+
console.log('Active:', gameSession.active);
157+
158+
const startTime = hexToDate(gameSession.start_time);
159+
const lastUpdate = hexToDate(gameSession.last_update);
160+
161+
console.log('\nStart time:', startTime.localTime, `(${startTime.relative})`);
162+
console.log('Last update:', lastUpdate.localTime, `(${lastUpdate.relative})`);
163+
164+
const startTimestamp = parseInt(gameSession.start_time.replace(/^0x/, ''), 16);
165+
const lastUpdateTimestamp = parseInt(gameSession.last_update.replace(/^0x/, ''), 16);
166+
const duration = lastUpdateTimestamp - startTimestamp;
167+
console.log('Session duration:', formatDuration(duration));
168+
console.log('====================');
169+
}
170+
171+
// Run the script
172+
processGameSessions();

0 commit comments

Comments
 (0)