Skip to content
Open
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ In order to use this library you need to have access to an Oracle Field Service
- `params.expand` (array): Include sub-entities like inventories, workZones, workSkills
- `params.fields` (array): Specify which resource fields to return

`updateResource(resourceId, data, params?)`: Update an existing resource

- `data` (object): Resource fields to update, including supported built-in fields and custom properties
- `params.identifyResourceBy` (`"resourceId"` or `"resourceInternalId"`): Specify whether `resourceId` is an external resource ID or OFS internal ID

`getResources(params?)`: Get existing resources with optional filtering parameters

- `params.canBeTeamHolder` (boolean): Filter resources that can be team holders
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
],
"name": "@ofs-users/proxy",
"type": "module",
"version": "1.30.0",
"version": "1.31.0",
"description": "A Javascript proxy to access Oracle Field Service via REST API",
"main": "dist/ofs.es.js",
"module": "dist/ofs.es.js",
Expand Down
65 changes: 61 additions & 4 deletions src/OFS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
OFSBulkUpdateRequest,
OFSGetResourcesParams,
OFSGetResourceParams,
OFSUpdateResourceParams,
OFSUpdateResourceRequest,
OFSGetResourceAssistantsParams,
OFSResourceResponse,
OFSSingleResourceResponse,
Expand Down Expand Up @@ -165,8 +167,16 @@ export class OFS {
return fetchPromise;
}

private _patch(partialURL: string, data: any): Promise<OFSResponse> {
private _patch(
partialURL: string,
data: any,
params: any = undefined
): Promise<OFSResponse> {
var theURL = new URL(partialURL, this._baseURL);
if (params != undefined) {
const urlSearchParams = new URLSearchParams(params);
theURL.search = urlSearchParams.toString();
}
var myHeaders = new Headers();
myHeaders.append("Authorization", this.authorization);
myHeaders.append("Content-Type", "application/json");
Expand All @@ -178,15 +188,36 @@ export class OFS {
const fetchPromise = fetch(theURL, requestOptions)
.then(async function (response) {
// Your code for handling the data you get from the API
var responseData;
var contentType = response.headers.get("Content-Type") || undefined;
try {
if (response.status != 204) {
if (contentType?.includes("json")) {
responseData = await response.json();
} else if (contentType?.includes("text")) {
responseData = await response.text();
} else {
responseData = await response.blob();
}
}
} catch (error) {
responseData = undefined;
}
if (response.status < 400) {
var data = await response.json();
return new OFSResponse(theURL, response.status, undefined, data);
return new OFSResponse(
theURL,
response.status,
undefined,
responseData,
contentType
);
} else {
return new OFSResponse(
theURL,
response.status,
response.statusText,
undefined
responseData,
contentType
);
}
})
Expand Down Expand Up @@ -727,6 +758,32 @@ export class OFS {
);
}

/**
* Updates an existing resource.
* @param resourceId The resource external ID or internal ID, depending on params.identifyResourceBy
* @param data Resource fields to update
* @param params Optional query parameters for identifying the resource
* @returns The updated resource details
*/
async updateResource(
resourceId: string,
data: OFSUpdateResourceRequest,
params: OFSUpdateResourceParams = {}
): Promise<OFSSingleResourceResponse> {
const partialURL = `/rest/ofscCore/v1/resources/${resourceId}`;
const queryParams: any = {};

if (params.identifyResourceBy !== undefined) {
queryParams.identifyResourceBy = params.identifyResourceBy;
}

return this._patch(
partialURL,
data,
Object.keys(queryParams).length > 0 ? queryParams : undefined
) as Promise<OFSSingleResourceResponse>;
}

/**
* Retrieves assistants for a given resource.
* @param resourceId The ID of the resource
Expand Down
24 changes: 24 additions & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,30 @@ export interface OFSResource {
timeZone?: string;
}

export type OFSIdentifyResourceBy = "resourceId" | "resourceInternalId";

export interface OFSUpdateResourceParams {
identifyResourceBy?: OFSIdentifyResourceBy;
}

export interface OFSUpdateResourceRequest {
dateFormat?: "dd/mm/yy" | "mm/dd/yy" | "dd.mm.yy" | "yyyy/mm/dd" | null;
durationStatisticsInitialPeriod?: number | null;
durationStatisticsInitialRatio?: number;
email?: string | null;
language?: string;
name?: string;
organization?: string | null;
parentResourceId?: string;
phone?: string | null;
resourceId?: string | null;
resourceType?: string;
status?: "active" | "inactive";
timeFormat?: "12-hour" | "24-hour" | null;
timeZone?: string;
[key: string]: any;
}

export interface OFSResourceListResponse {
totalResults: number;
limit: number;
Expand Down
100 changes: 100 additions & 0 deletions test/unit/updateResource.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright © 2022, 2023, Oracle and/or its affiliates.
* Licensed under the Universal Permissive License (UPL), Version 1.0 as shown at https://oss.oracle.com/licenses/upl/
*/

import { OFS } from "../../src/OFS";
import { OFSUpdateResourceRequest } from "../../src/model";

const originalFetch = global.fetch;
const fetchMock = jest.fn();

function jsonResponse(status: number, data: any, statusText = "OK"): Response {
return {
status,
statusText,
headers: new Headers({ "Content-Type": "application/json" }),
json: jest.fn().mockResolvedValue(data),
} as unknown as Response;
}

function createProxy(): OFS {
return new OFS({
baseURL: "https://example.test",
token: "test-token",
});
}

beforeEach(() => {
fetchMock.mockReset();
global.fetch = fetchMock;
});

afterAll(() => {
global.fetch = originalFetch;
});

test("updateResource sends PATCH to the resource endpoint", async () => {
const payload: OFSUpdateResourceRequest = {
name: "Updated Technician",
status: "active",
customTextProperty: "kept",
};
const responseData = {
resourceId: "TECH_1",
name: "Updated Technician",
status: "active",
resourceType: "field_resource",
customTextProperty: "kept",
};
fetchMock.mockResolvedValue(jsonResponse(200, responseData));

const result = await createProxy().updateResource("TECH_1", payload);
const [url, options] = fetchMock.mock.calls[0];

expect(url.toString()).toBe(
"https://example.test/rest/ofscCore/v1/resources/TECH_1"
);
expect(options.method).toBe("PATCH");
expect(options.body).toBe(JSON.stringify(payload));
expect(options.headers.get("Authorization")).toBe("Bearer test-token");
expect(options.headers.get("Content-Type")).toBe("application/json");
expect(result.status).toBe(200);
expect(result.data).toEqual(responseData);
});

test("updateResource serializes identifyResourceBy", async () => {
fetchMock.mockResolvedValue(
jsonResponse(200, {
resourceId: "TECH_2",
name: "Updated Technician",
status: "active",
resourceType: "field_resource",
})
);

await createProxy().updateResource(
"12345",
{ resourceId: "TECH_2" },
{ identifyResourceBy: "resourceInternalId" }
);
const [url] = fetchMock.mock.calls[0];

expect(url.toString()).toBe(
"https://example.test/rest/ofscCore/v1/resources/12345?identifyResourceBy=resourceInternalId"
);
});

test("updateResource preserves error status and response body", async () => {
const errorData = {
title: "Invalid resource",
detail: "Resource does not exist",
};
fetchMock.mockResolvedValue(jsonResponse(404, errorData, "Not Found"));

const result = await createProxy().updateResource("UNKNOWN", {});

expect(result.status).toBe(404);
expect(result.description).toBe("Not Found");
expect(result.data).toEqual(errorData);
});
Loading