-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
226 lines (199 loc) · 5.91 KB
/
Copy pathserver.js
File metadata and controls
226 lines (199 loc) · 5.91 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4');
const express = require('express');
const cors = require('cors');
const http = require('http');
const path = require('path');
const fs = require('fs');
const { tarkovLandingPagePlugin } = require('./tarkovLandingPage');
// ---------------------
// Data loading (with robust local -> cache -> GitHub fetch fallback)
// ---------------------
const dataDir = path.join(__dirname, '..', 'TarkovData', 'data');
let cachedQuests = null;
async function loadQuests() {
if (cachedQuests) {
return cachedQuests;
}
// Try 1: Remote data server data.tarkovlab.org
try {
console.log('Fetching quests from remote data server https://data.tarkovlab.org/quests.json ...');
const response = await fetch('https://data.tarkovlab.org/quests.json');
if (response.ok) {
const text = await response.text();
cachedQuests = JSON.parse(text);
console.log('Successfully loaded quests from data.tarkovlab.org.');
// Save/Cache locally as backup
try {
const apiLocalPath = path.join(__dirname, 'data', 'quests.json');
const apiLocalDir = path.dirname(apiLocalPath);
if (!fs.existsSync(apiLocalDir)) {
fs.mkdirSync(apiLocalDir, { recursive: true });
}
fs.writeFileSync(apiLocalPath, text, 'utf8');
} catch (writeErr) {
console.warn('Could not cache remote quests locally:', writeErr.message);
}
return cachedQuests;
} else {
console.warn(`Failed to fetch from data.tarkovlab.org: HTTP ${response.status}`);
}
} catch (e) {
console.warn('Could not fetch from data.tarkovlab.org:', e.message);
}
// Try 2: Local backup cache
try {
const apiLocalPath = path.join(__dirname, 'data', 'quests.json');
if (fs.existsSync(apiLocalPath)) {
const raw = fs.readFileSync(apiLocalPath, 'utf8');
cachedQuests = JSON.parse(raw);
console.log('Successfully loaded quests from local cache backup.');
return cachedQuests;
}
} catch (e) {
console.warn('Could not load quests from local cache backup:', e.message);
}
// Try 3: Sibling TarkovData repository (local development fallback)
try {
const localPath = path.join(dataDir, 'quests.json');
if (fs.existsSync(localPath)) {
const raw = fs.readFileSync(localPath, 'utf8');
cachedQuests = JSON.parse(raw);
console.log('Successfully loaded quests from local TarkovData sibling directory.');
return cachedQuests;
}
} catch (e) {
console.warn('Could not load quests from local TarkovData:', e.message);
}
// Try 4: GitHub backup fallback
try {
console.log('Fetching quests from GitHub repository backup...');
const url = 'https://raw.githubusercontent.com/TarkovLab/TarkovData/master/data/quests.json';
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const text = await response.text();
cachedQuests = JSON.parse(text);
return cachedQuests;
} catch (e) {
console.error('Failed to load quests from all sources:', e.message);
throw e;
}
}
// ---------------------
// GraphQL Schema
// ---------------------
const typeDefs = `#graphql
type GPS {
leftPercent: Float
topPercent: Float
floor: String
}
type Objective {
id: Int
type: String
target: String
number: Int
location: Int
gps: GPS
}
type Reputation {
trader: Int
rep: Float
}
type QuestRequirement {
level: Int
quests: [Int]
}
type Locales {
en: String
ru: String
cs: String
}
type Quest {
id: Int!
title: String!
locales: Locales
wiki: String
exp: Int
giver: Int
turnin: Int
gameId: String
require: QuestRequirement
unlocks: [String]
reputation: [Reputation]
objectives: [Objective]
}
type Query {
"""Get all quests"""
quests: [Quest!]!
"""Get a single quest by its id"""
quest(id: Int!): Quest
"""Get quests given by a specific trader (by trader index)"""
questsByTrader(trader: Int!): [Quest!]!
}
`;
// ---------------------
// Resolvers
// ---------------------
const resolvers = {
Objective: {
target: (parent) => {
if (Array.isArray(parent.target)) {
return JSON.stringify(parent.target);
}
return parent.target !== undefined && parent.target !== null ? String(parent.target) : null;
},
},
Query: {
quests: async () => await loadQuests(),
quest: async (_, { id }) => {
const quests = await loadQuests();
return quests.find((q) => q.id === id) || null;
},
questsByTrader: async (_, { trader }) => {
const quests = await loadQuests();
return quests.filter((q) => q.giver === trader);
},
},
};
// ---------------------
// Server bootstrap
// ---------------------
async function startServer() {
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
// Enable the embedded Apollo Sandbox (playground) in all environments
introspection: true,
plugins: [tarkovLandingPagePlugin],
});
await server.start();
// Health check – classic REST endpoint
app.get('/health', (_req, res) => {
res.status(200).json({ status: 'OK' });
});
// GraphQL endpoint with Apollo Sandbox as playground
app.use(
'/graphql',
cors(),
express.json(),
expressMiddleware(server),
);
// Redirect root to playground
app.get('/', (_req, res) => {
res.redirect('/graphql');
});
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`🚀 Server ready at http://localhost:${PORT}/graphql`);
console.log(`❤️ Health check at http://localhost:${PORT}/health`);
});
}
startServer().catch((err) => {
console.error('Failed to start server:', err);
process.exit(1);
});