Skip to content

Commit

Permalink
Merge pull request #7 from FuelRats/apiv3-support
Browse files Browse the repository at this point in the history
feat(api): Updated to APIv3 compatibility
  • Loading branch information
itssimple authored Sep 27, 2020
2 parents 1c55c9f + a4dbd87 commit 6cce326
Show file tree
Hide file tree
Showing 8 changed files with 184 additions and 126 deletions.
25 changes: 19 additions & 6 deletions src/Components/BoardView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,28 @@ class BoardView extends React.Component<BoardProps> {
<tr
key={rescue.id}
className="rescueRow"
onClick={e => this.selectRescue(rescue.id, e)}
onClick={(e) => this.selectRescue(rescue.id, e)}
>
<td align={"center"}>#{rescue.attributes.data.boardIndex}</td>
<td align={"center"}>{rescue.attributes.platform != null ? rescue.attributes.platform.toUpperCase() : 'unknown'}</td>
<td align={"center"}>#{rescue.attributes.commandIdentifier}</td>
<td align={"center"}>
{rescue.attributes.platform != null
? rescue.attributes.platform.toUpperCase()
: "unknown"}
</td>
<td>{rescue.attributes.client}</td>
<td onClick={e => copySystemName(rescue.attributes.system, e)}>{rescue.attributes.system}</td>
<td align={"center"}>{rescue.attributes.codeRed != null && rescue.attributes.codeRed ? "✅" : "❌"}</td>
<td onClick={(e) => copySystemName(rescue.attributes.system, e)}>
{rescue.attributes.system}
</td>
<td align={"center"}>
{rescue.attributes.codeRed != null && rescue.attributes.codeRed
? "✅"
: "❌"}
</td>
<td align={"center"}>
{rescue.attributes.status == null || rescue.attributes.status === "open" ? "✅" : "❌"}
{rescue.attributes.status == null ||
rescue.attributes.status === "open"
? "✅"
: "❌"}
</td>
<td colSpan={2}>
{rescue.relationships.rats.data &&
Expand Down
14 changes: 9 additions & 5 deletions src/Components/SelectedCaseView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ class SelectedCaseView extends React.Component<RatDataProps> {
constructor(props: RatDataProps) {
super(props);
autorun(() => {
console.log(this.props.store.selectedRescue);
this.fetchRescueInfo(this.props.store.selectedRescue);
});
}
Expand All @@ -17,7 +16,6 @@ class SelectedCaseView extends React.Component<RatDataProps> {

fetchRescueInfo(rescueId: string) {
if (!rescueId) {
console.log("No rescue selected");
this.selectedRescue = null;
} else {
if (!!this.props.store.rescues[rescueId]) {
Expand All @@ -43,7 +41,13 @@ class SelectedCaseView extends React.Component<RatDataProps> {
</tr>
<tr>
<td>System:</td>
<td onClick={e => copySystemName(this.selectedRescue.attributes.system, e)}>{this.selectedRescue.attributes.system}</td>
<td
onClick={(e) =>
copySystemName(this.selectedRescue.attributes.system, e)
}
>
{this.selectedRescue.attributes.system}
</td>
</tr>
<tr>
<td>Status:</td>
Expand Down Expand Up @@ -88,8 +92,8 @@ class SelectedCaseView extends React.Component<RatDataProps> {
</tbody>
</table>
) : (
<i>No rescue selected</i>
)}
<i>No rescue selected</i>
)}
</div>
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ export const RatConfig = {
ApiUri: "https://api.fuelrats.com",
SystemApiUri: "https://system.api.fuelrats.com/",
ClientId: "0f107a5f-e0d9-4fe8-a9ae-66386cbfc6cd",
Scope: "user.read.me rescue.read",
WebUri: "https://fuelrats.com",
Scope: "users.read.me rescues.read",
WebUri: "https://www.fuelrats.com",
WssUri: "wss://api.fuelrats.com",
RandomState(): string {
return this.rand(20, "-rattracker");
Expand All @@ -21,5 +21,5 @@ export const RatConfig = {
) + current
)
: current;
}
},
};
134 changes: 72 additions & 62 deletions src/Lib/Api/RatSocket.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,31 @@ import { RatConfig } from "../../Config";
export class RatSocket extends RatEmitter {
private socket: WebSocket | null;
private currentToken: string | null;
private clientId: string | null;
private welcomeTimeout: number | null;
private openRequests: any;
public connected: boolean;
constructor() {
super(true, [
"rescueCreated",
"rescueUpdated",
"rescueDeleted",
"fuelrats.rescuecreate",
"fuelrats.rescueupdate",
"fuelrats.rescuedelete",
"rattracker.friendrequest",
"rattracker.wingrequest",
"rattracker.systemreached",
"connection",
"ratsocket:connect",
"ratsocket:disconnect",
"ratsocket:error",
"ratsocket:reconnect"
"ratsocket:reconnect",
]);

this.socket = null;
this.currentToken = null;
this.clientId = RatConfig.GetRequestId("rtClient");
this.welcomeTimeout = null;
this.openRequests = {};
this.connected = false;

window.setInterval(this.checkConnectionAndReconnectIfNeeded, 30000);
window.setInterval(() => this.checkConnectionAndReconnectIfNeeded(), 30000);
}

async connect(token: string) {
Expand All @@ -42,19 +43,19 @@ export class RatSocket extends RatEmitter {
code: 408,
detail: "No response from server",
status: "Request Timeout",
title: "Request Timeout"
}
title: "Request Timeout",
},
],
meta: {}
meta: {},
});
}, 60000);

let onConnect = (data: Object) => {
window.clearTimeout(this.welcomeTimeout!);
this.off("ratsocket:error", onError);
this._emitEvent("ratsocket:connect", data);
resolve(data);
},
window.clearTimeout(this.welcomeTimeout!);
this.off("ratsocket:error", onError);
this._emitEvent("ratsocket:connect", data);
resolve(data);
},
onError = (data: Object) => {
window.clearTimeout(this.welcomeTimeout!);
this.off("connection", onConnect);
Expand All @@ -64,29 +65,30 @@ export class RatSocket extends RatEmitter {
code: 500,
detail: data,
status: "Error.",
title: "Error."
}
title: "Error.",
},
],
meta: {}
meta: {},
});
};

this.once("connection", onConnect)!.once("ratsocket:error", onError);

this.socket = new WebSocket(
`${RatConfig.WssUri}?bearer=${this.currentToken}`
`${RatConfig.WssUri}?bearer=${this.currentToken}`,
"FR-JSONAPI-WS"
);
this.socket.onopen = () => {
this.connectionOpened();
};
this.socket.onclose = data => {
this.socket.onclose = (data) => {
this.connectionClosed(data);
};
this.socket.onerror = data => {
this.socket.onerror = (data) => {
this.errorReceived(data);
reject(data);
};
this.socket.onmessage = data => {
this.socket.onmessage = (data) => {
this.messageReceived(data);
};
});
Expand All @@ -109,33 +111,34 @@ export class RatSocket extends RatEmitter {
}

messageReceived(data: any) {
window.console.debug("RatTracker incoming data: " + data.data);
window.console.debug("RatTracker incoming data: ", data.data);

let _data = JSON.parse(data.data);

if (
_data.meta.reqId &&
this.openRequests.hasOwnProperty(_data.meta.reqId)
) {
this.openRequests[_data.meta.reqId](_data);
delete this.openRequests[_data.meta.reqId];
} else if (_data.meta.event) {
console.log(_data.meta.event);
this._emitEvent(_data.meta.event, _data);
if (_data[0] && this.openRequests.hasOwnProperty(_data[0])) {
this.openRequests[_data[0]](_data);
delete this.openRequests[_data[0]];
} else if (_data[0]) {
this._emitEvent(_data[0], _data);
} else {
window.console.warn(_data);
}
}

async checkConnectionAndReconnectIfNeeded() {
if (this.socket && this.socket!.readyState !== 1 && this.socket!.readyState > 1) {
if (
this.socket &&
this.socket!.readyState !== 1 &&
this.socket!.readyState > 1
) {
await this.connect(this.currentToken!);
}

return this;
}

async send(payload: Object) {
console.log("RatSocket::Send", payload);
if (this.socket!.readyState !== 1) {
if (this.socket!.readyState > 1) {
await this.connect(this.currentToken!);
Expand All @@ -150,59 +153,66 @@ export class RatSocket extends RatEmitter {
return this;
}

request(msg: any) {
if (typeof msg !== "object") {
throw new TypeError("I want an object");
}

if (!Array.isArray(msg.action) || msg.action.length !== 2) {
request(
endpoint: Array<string>,
query?: any,
body?: any
): Promise<Array<any>> {
if (!Array.isArray(endpoint) || endpoint.length < 1) {
throw new RangeError("You must supply an array with two items.");
}

if (!msg.meta) {
msg.meta = {};
}

if (!msg.meta.reqId) {
msg.meta.reqId = RatConfig.GetRequestId("req");
}

msg.meta.clientId = this.clientId;

if (!msg.data) {
msg.data = {};
}

return new Promise((resolve, reject) => {
let requestId = msg.meta.reqId;
let reqId = RatConfig.GetRequestId("req");
let cmd_timeout = window.setTimeout(() => {
reject({
errors: [
{
code: 408,
detail: "Server produced no response.",
status: "Request Timeout",
title: "Request Timeout"
}
title: "Request Timeout",
},
],
meta: msg.meta
});
}, 15000);

this.openRequests[requestId] = (response: any) => {
this.openRequests[reqId] = (response: any) => {
window.clearTimeout(cmd_timeout);
if (response.errors) {
reject(response);
}
resolve(response);
};

this.send(msg);
let requestObject = [reqId, endpoint];

if (query) {
requestObject.push(query);
}

if (body) {
requestObject.push(body);
}

this.send(requestObject);
});
}

subscribe(channel: string) {
let msg = { action: ["stream", "subscribe"], id: channel };
return this.request(msg);
subscribe() {
return this.request(
["events", "subscribe"],
{
events: [
"fuelrats.rescuecreate",
"fuelrats.rescueupdate",
"fuelrats.rescuedelete",
"rattracker.friendrequest",
"rattracker.wingrequest",
"rattracker.systemreached",
],
},
null
);
}
}
2 changes: 1 addition & 1 deletion src/Lib/Auth/Auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class Auth {
RatConfig.ClientId
}&scope=${encodeURI(RatConfig.Scope)}&state=${encodeURI(
RatConfig.RandomState()
)}&response_type=token`;
)}&response_type=token&redirect_uri=http://rattracker/auth`;
}
}

Expand Down
Loading

0 comments on commit 6cce326

Please sign in to comment.