Skip to content

Commit

Permalink
Merge pull request #341 from BritishYouthBandAssociation/luke-payload…
Browse files Browse the repository at this point in the history
…-events

Use Payload API for Events
  • Loading branch information
rugulous authored Aug 28, 2023
2 parents ca84382 + 025b840 commit 542cc3f
Show file tree
Hide file tree
Showing 13 changed files with 777 additions and 1,260 deletions.
3 changes: 2 additions & 1 deletion config/server.sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"noAuthRequired": ["/", "/organisation/new", "/organisation/registration/"],
"logging": true,
"uploadServer": "",
"uploadSecret": ""
"uploadSecret": "",
"apiBase": "https://payload.byba.online/api"
}
2 changes: 1 addition & 1 deletion public/css/site.css
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ body {
animation: fade-up ease-in-out 3s;
}

.accordion-button[disabled] {
.accordion-button[disabled], .disabled {
opacity: 60%;
}

Expand Down
177 changes: 177 additions & 0 deletions public/js/byba-sdk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
'use strict';

/* global BASE_API */

let byba = {};

Check warning on line 5 in public/js/byba-sdk.js

View workflow job for this annotation

GitHub Actions / lint

'byba' is assigned a value but never used. Allowed unused vars must match /^_/u

(function() {
let user = JSON.parse(localStorage.getItem('user'));

function getTimeFromDate(date){
return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

function formatEvent(event){
const startDate = new Date(event.start);
const endDate = new Date(event.end);
const eventDate = new Date(startDate.toDateString());

delete event.start;
delete event.end;

return {
...event,
date: eventDate,
startTime: getTimeFromDate(startDate),
endTime: getTimeFromDate(endDate)
};
}

async function makeAPIRequest(url, options = {}) {
options.credentials = 'include';
options.headers ??= {};
options.headers['Content-Type'] = 'application/json';

try {
const response = await fetch(`${BASE_API}${url}`, options);
const json = await response.json();

const result = {
status: response.status,
json,
success: Math.floor(response.status / 100) === 2
};

if (json.errors) {
result.errors = json.errors.flatMap(e => {
if (e.name === 'ValidationError' && e.data) {
return e.data.map(d => `${d.field} is invalid: ${d.message}`);
}

return e.message;
});
}

return result;
} catch (ex){
//usually only network interruptions?
return {
status: 500,
exception: ex,
success: false,
errors: ['An unexpected error occurred. Please try again!']
};
}
}

//Read
async function get(url, queryParams = null) {
if (queryParams != null) {
url += `?${new URLSearchParams(queryParams)}`;
}

return await makeAPIRequest(url);
}

//Create
async function post(url, body) {
return await makeAPIRequest(url, {
method: 'POST',
body: JSON.stringify(body),
});
}

//Update
async function patch(url, body) {
return await makeAPIRequest(url, {
method: 'PATCH',
body: JSON.stringify(body)
});
}

byba = {
async login(email, password) {
const response = await post('/users/login', { email, password });

if (response.success){
user = response.json.user;
localStorage.setItem('user', JSON.stringify(user));
}

return response;
},

amAdmin() {
return user?.role === 'admin';
},

creator(resource = null) {
return resource?.createdBy === user.id;
},

events: {
async list(season, {sort = true, after = null} = {}) {
const query = {
'where[season][equals]': season
};

if (sort){
query.sort = 'start';
}

if (after){
query['where[start][greater_than]'] = after;
}

const response = await get('/events', query);
if (response.success){
response.json.docs = response.json.docs.map(d => formatEvent(d));
}
return response;
},

async get(id) {
const response = await get(`/events/${id}`);
if (response.success){
response.json = formatEvent(response.json);
}
return response;
},

async update(id, name, date, startTime, endTime, status, address, season = null) {
const start = new Date(`${date}T${startTime}`);
const end = new Date(`${date}T${endTime}`);

const data = {
name,
start,
end,
status,
address
};

if (season){
data.season = season;
}

return await patch(`/events/${id}`, data);
},

async create(name, date, startTime, endTime) {
const start = new Date(`${date}T${startTime}`);
const end = new Date(`${date}T${endTime}`);
return await post('/events/', { name, start, end });
}
},

seasons: {
async getCurrent() {
return await get('/seasons/current');
},

async list() {
return await get('/seasons');
}
}
};
})();
5 changes: 5 additions & 0 deletions public/js/site.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
'use strict';

function getDate(rawDate) {
const date = new Date(rawDate);
return [date.getFullYear(), (date.getMonth() + 1).toString().padStart(2, '0'), date.getDate().toString().padStart(2, '0')].join('-');
}

(function() {
function initDropdownStyleHelper() {
const els = document.querySelectorAll('select.style-by-value');
Expand Down
Loading

0 comments on commit 542cc3f

Please sign in to comment.