Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 36 additions & 32 deletions jslib/http/Client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
declare const loris: any;
import {Query, QueryParam} from './Query';
import {Errors} from '../';

Expand Down Expand Up @@ -51,22 +50,7 @@ export class Client<T> {
* @param query A Query object to build the URL query string.
*/
async get<U = T>(query?: Query): Promise<U[]> {
// 1. Determine the path to resolve
const relativePath = this.subEndpoint ? this.subEndpoint : '';

// 2. Create the full URL object by resolving the path against this.baseURL.
const url = new URL(relativePath, this.baseURL);

// 3. Add Query Parameters using the URL object's searchParams
if (query) {
const params = new URLSearchParams(query.build());
params.forEach((value, key) => {
url.searchParams.append(key, value);
});
}

// 4. Use the final URL object for the fetch request.
return this.fetchJSON<U[]>(url, {
return this.fetchJSON<U[]>(this.buildURL('', query), {
method: 'GET',
headers: {'Accept': 'application/json'},
});
Expand All @@ -89,11 +73,7 @@ export class Client<T> {
* @param id The unique identifier of the resource to fetch.
*/
async getById(id: string): Promise<T> {
// 1. Resolve the ID as a path segment against the this.baseURL object.
const url = new URL(id, this.baseURL);

// 2. Pass the final URL string to fetchJSON
return this.fetchJSON<T>(url, {
return this.fetchJSON<T>(this.buildURL(id), {
method: 'GET',
headers: {'Accept': 'application/json'},
});
Expand All @@ -107,7 +87,7 @@ export class Client<T> {
*/
async create<U = T>(data: T, mapper?: (data: T) => U): Promise<T> {
const payload = mapper ? mapper(data) : data;
return this.fetchJSON<T>(this.baseURL, {
return this.fetchJSON<T>(this.buildURL(), {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload),
Expand All @@ -121,11 +101,7 @@ export class Client<T> {
* @param data The new resource data.
*/
async update(id: string, data: T): Promise<T> {
// 1. Resolve the ID as a path segment against the this.baseURL object.
const url = new URL(id, this.baseURL);

// 2. Pass the final URL string to fetchJSON
return this.fetchJSON<T>(url, {
return this.fetchJSON<T>(this.buildURL(id), {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
Expand All @@ -143,6 +119,7 @@ export class Client<T> {
options: RequestInit
): Promise<U> {
const request = new Request(url, options);

try {
const response = await fetch(request);

Expand All @@ -155,7 +132,12 @@ export class Client<T> {
);
}

// Handle responses with no content or non-JSON content
// 2. Handle HTTP 204 No Content (Success, but nothing to parse)
if (response.status === 204) {
return {} as U;
}

// 3. Validate JSON Content-Type
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Errors.NoContent(
Expand All @@ -165,7 +147,7 @@ export class Client<T> {
);
}

// 2. Handle JSON parsing errors
// 4. Parse JSON
try {
const data = await response.json();
return data as U;
Expand All @@ -174,12 +156,34 @@ export class Client<T> {
throw new Errors.JsonParse(request, message);
}
} catch (error) {
// 3. Handle network errors (e.g., no internet)
if (error instanceof Errors.Http) {
// 5. Re-throw custom errors; wrap native network errors
if (error instanceof Errors.Http || error instanceof Errors.ApiResponse) {
throw error; // Re-throw our custom errors
}
const message = this.getErrorMessage('ApiNetworkError', request);
throw new Errors.ApiNetwork(request, message);
}
}

/**
* Constructs a full URL by combining the base URL, sub-endpoint,
* and an optional path or resource ID, then appends query parameters.
*
* @param path - An optional sub-path or resource ID (e.g., '123' or 'details').
* Defaults to an empty string.
* @param query - An optional Query object used to build the URL's search parameters.
* @returns A fully constructed URL object.
*/
private buildURL(path = '', query?: Query): URL {
// 1. Resolve segments (this.baseURL + subEndpoint + id/path)
const segments = [this.subEndpoint, path].filter(Boolean).join('/');
const url = new URL(segments, this.baseURL);

// 2. Append the pre-built query string
if (query) {
url.search = query.build();
}

return url;
}
}
24 changes: 13 additions & 11 deletions jslib/http/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ export interface QueryParam {
*/
export class Query {
private params: Record<string, string> = {};
private selectedFields: string[] = [];

/**
* Adds a filter parameter to the query string.
* TODO: Add support for multiple values for same field
*
* @param root0 The destructured QueryParam object.
* @param root0.field The field to filter on.
Expand All @@ -34,9 +36,7 @@ export class Query {
value,
operator = Operator.Equals,
}: QueryParam): this {
const encodedField = encodeURIComponent(field);
const encodedValue = encodeURIComponent(value);
this.params[`${encodedField}${operator}`] = encodedValue;
this.params[`${field}${operator}`] = value;
return this;
}

Expand All @@ -46,11 +46,8 @@ export class Query {
* @param field The field to include in the response payload.
*/
addField(field: string): this {
const encodedField = encodeURIComponent(field);
if (this.params['fields']) {
this.params['fields'] = `${this.params['fields']},${encodedField}`;
} else {
this.params['fields'] = encodedField;
if (!this.selectedFields.includes(field)) {
this.selectedFields.push(field);
}
return this;
}
Expand Down Expand Up @@ -82,15 +79,20 @@ export class Query {
* @param direction The sort direction.
*/
addSort(field: string, direction: 'asc' | 'desc'): this {
const encodedField = encodeURIComponent(field);
this.params['sort'] = `${encodedField}:${direction}`;
this.params['sort'] = `${field}:${direction}`;
return this;
}

/**
* Builds and returns the final URL search string.
*/
build(): string {
return new URLSearchParams(this.params).toString();
const finalParams = {...this.params};

if (this.selectedFields.length > 0) {
finalParams['fields'] = this.selectedFields.join(',');
}

return new URLSearchParams(finalParams).toString();
}
}
53 changes: 15 additions & 38 deletions modules/acknowledgements/jsx/acknowledgementsIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,50 +153,29 @@ class AcknowledgementsIndex extends Component {
*
* @param {event} e - event of the form
*/
handleSubmit(e) {
async handleSubmit(e) {
e.preventDefault(); // prevent default form submission
const {formData, submitting} = this.state;

if (submitting) return; // prevent multiple submits

this.setState({submitting: true}); // set submitting to true

let formObject = new FormData();
for (let key in formData) {
if (formData[key] !== '') {
formObject.append(key, formData[key]);
}
}
formObject.append('fire_away', 'Add');
try {
const client = new Acknowledgement.Client()
.setSubEndpoint('AcknowledgementsProcess');
await client.create(formData);

fetch(this.props.submitURL, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
body: formObject,
})
.then((resp) => {
if (resp.ok && resp.status === 200) {
swal
.fire('Success!', 'Acknowledgement added.', 'success')
.then((result) => {
if (result.value) {
this.closeModalForm();
this.fetchData();
}
});
} else {
resp.text().then((message) => {
swal.fire('Error!', message, 'error');
});
}
})
.catch((error) => {
console.error(error);
})
.finally(() => {
this.setState({submitting: false}); // reset submitting state
});
await swal.fire('Success!', 'Acknowledgement added.', 'success');
this.closeModalForm();
this.fetchData();
} catch (error) {
const message = error.message || 'An unexpected error occurred.';
swal.fire('Error!', message, 'error');
console.error(error);
} finally {
this.setState({submitting: false});
}
}

/**
Expand Down Expand Up @@ -481,7 +460,6 @@ class AcknowledgementsIndex extends Component {
}

AcknowledgementsIndex.propTypes = {
submitURL: PropTypes.string.isRequired,
hasPermission: PropTypes.func.isRequired,
};

Expand All @@ -494,7 +472,6 @@ window.addEventListener('load', () => {
document.getElementById('lorisworkspace')
).render(
<Index
submitURL={`${loris.BaseURL}/acknowledgements/AcknowledgementsProcess`}
hasPermission={loris.userHasPermission}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ export class AcknowledgementClient extends Http.Client<Acknowledgement.Type> {
*
*/
constructor() {
super('/acknowledgements');
super('acknowledgements');
}
}
22 changes: 14 additions & 8 deletions modules/acknowledgements/php/acknowledgementsprocess.class.inc
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class Acknowledgementsprocess extends \NDB_Page
$affiliations = "";
$degrees = "";
$roles = "";
$values = $req->getParsedBody();
$values = json_decode($req->getBody()->getContents(), true);
if (isset($values) && !is_null($values)) {
if (isset($values['addPresent']) && $values['addPresent'] === 'Yes') {
$values['addEndDate'] = null;
Expand Down Expand Up @@ -106,13 +106,19 @@ class Acknowledgementsprocess extends \NDB_Page

$DB->insert('acknowledgements', $results);
unset($values);
$baseURL = \NDB_Factory::singleton()->settings()->getBaseURL();
return (new \LORIS\Http\Response())
->withStatus(200)
->withHeader(
"Location",
"{$baseURL}/acknowledgements/"
);
$baseURL = \NDB_Factory::singleton()->settings()->getBaseURL();

// 2. Access the public property (no parentheses!)
$newId = $DB->lastInsertID;

// 4. Return the Created response
return new \LORIS\Http\Response\JSON\Created(
[
"message" => "Acknowledgement added.",
"id" => $newId
],
["Location" => "{$baseURL}/api/v1/acknowledgements/{$newId}"]
);
}
}

Expand Down
Loading