Trailheadの課題に苦戦したので自分メモ…。
長いこと投稿してなかったけど、生きてますよ\(^o^)/
Create a Service and Implement a Caller.
Create an Apex class that is a service that exposes a bulkified service method. The service closes and sets the reason for one or more given case records. Implement an Apex REST class that calls this service.
https://trailhead.salesforce.com/ja/content/learn/modules/apex_patterns_sl/apex_patterns_sl_apply_sl_principles
- Create an Apex class called CaseService that contains a void static method called closeCases that takes a set of Case IDs and a String parameter for the close reason.
- Create a REST Apex class called CaseCloseResource with a URL mapping /case/*/close (where * will be the Id). Implement a POST closeCase method which accepts a String reason and calls the CaseService.closeCases service method passing in the Id and close reason.
必要なクラスは2つ。
サービスクラス「CaseService」と、公開用のAPIクラス「CaseCloseResource」を作る必要があります。
public with sharing class CaseService {
public static void closeCases(Set<Id> caseIds, String closeReason) {
if (caseIds == null || caseIds.isEmpty()) {
throw new CaseServiceException('No Case IDs provided.');
}
if (String.isEmpty(closeReason)) {
throw new CaseServiceException('Close reason is empty.');
}
List<Case> cases = [
SELECT Id, Status, Reason
FROM Case
WHERE Id IN :caseIds AND Status != 'Closed'
];
if (cases.isEmpty()) {
return;
}
for (Case c : cases) {
c.Status = 'Closed';
c.Reason = closeReason;
}
update cases;
}
public class CaseServiceException extends Exception {}
}
@RestResource(urlMapping='/case/*/close')
global with sharing class CaseCloseResource {
@HttpPost
global static void closeCase(String closeReason) {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
if(res == null) {
res = new RestResponse();
RestContext.response = res;
}
String caseIdStr = req.requestURI.substringBetween('case/', '/close');
if (String.isEmpty(caseIdStr) || String.isEmpty(closeReason)) {
res.statusCode = 400;
return;
}
Id caseId;
try {
caseId = Id.valueOf(caseIdStr);
} catch (Exception e) {
res.statusCode = 400;
return;
}
try {
CaseService.closeCases(new Set<Id>{caseId}, closeReason);
res.statusCode = 204; // No Content
} catch (CaseService.CaseServiceException e) {
res.statusCode = 500;
}
}
}
エラー出まくるので嫌になって、途中でChatGPTに投げたのは・・・げふんげふん(´・ω・`)
結局、自分のコードと見直して、間違ってたのは、値を設定する項目だったという…。
問題をよく理解してなくて、無駄にカスタムフィールド作ってたよ\(^o^)/
コメント