tenebrous-sheets/static/scripts/api.js

75 lines
2.7 KiB
JavaScript

function makeAPI(root) {
//Protobuf types
const UpdateAttributeRequestType = 'models.proto.cofd.api.UpdateAttributeRequest';
const UpdateAttributeRequest = root.lookupType(UpdateAttributeRequestType);
const UpdateSkillValueRequestType = 'models.proto.cofd.api.UpdateSkillValueRequest';
const UpdateSkillValueRequest = root.lookupType(UpdateSkillValueRequestType);
//TODO rpc-ify
const SkillSpecializationUpdateType = 'models.proto.cofd.api.SkillSpecializationsUpdate';
const SkillSpecializationsUpdate = root.lookupType(SkillSpecializationUpdateType);
const protobufContentType = (messageType) =>
({ 'Content-Type': 'application/x-protobuf; messageType="' + messageType + '"' });
const attributesResource = (username, characterID) =>
'/api/cofd/' + username + '/' + characterID + '/attributes';
const skillResource = (username, characterID, skillName) =>
'/api/cofd/' + username + '/' + characterID + '/skills';
function verifyAndCreate(protobufType, payload) {
let err = protobufType.verify(payload);
if (err) throw err;
return protobufType.create(payload);
}
async function updateAttribute(params) {
const { username, characterID, attribute, newValue } = params;
let req = verifyAndCreate(UpdateAttributeRequest, {
characterUsername: username,
characterId: parseInt(characterID),
attributeName: attribute,
attributeValue: parseInt(newValue)
});
let resp = await fetch('/api/rpc/cofd/update_attribute', {
method: 'POST',
headers: { ... protobufContentType(UpdateAttributeRequestType) },
body: UpdateAttributeRequest.encode(req).finish()
}).then(async resp => {
console.log("resp is", await resp.text());
}).catch(async err => {
console.log("err is", err.text());
});
}
async function updateSkillValue(params) {
const { username, characterID, skillName, newValue } = params;
let req = verifyAndCreate(UpdateSkillValueRequest, {
characterUsername: username,
characterId: parseInt(characterID),
skillName: skillName,
skillValue: parseInt(newValue)
});
let resp = await fetch('/api/rpc/cofd/update_skill_value', {
method: 'POST',
headers: { ... protobufContentType(UpdateSkillValueRequestType) },
body: UpdateSkillValueRequest.encode(req).finish()
}).then(async resp => {
console.log("resp is", await resp.text());
}).catch(async err => {
console.log("err is", err.text());
});
}
return {
updateAttribute,
updateSkillValue
};
}