Skip to content

Instantly share code, notes, and snippets.

@nuwanbando
Created March 27, 2020 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuwanbando/4b592d1acacd643994a2573e2e74cf2f to your computer and use it in GitHub Desktop.
Save nuwanbando/4b592d1acacd643994a2573e2e74cf2f to your computer and use it in GitHub Desktop.
import ballerina/http;
import ballerina/log;
import ballerina/stringutils;
// Service endpoint
listener http:Listener carEP = new(8090);
// Available car types
final string AC = "Air Conditioned";
final string NORMAL = "Normal";
// Car rental service to rent cars
@http:ServiceConfig {basePath:"/car"}
service carRentalService on carEP {
// Resource to rent a car
@http:ResourceConfig {methods:["POST"], path:"/rent", consumes:["application/json"], produces:["application/json"]}
resource function rentCar(http:Caller caller, http:Request request) returns @tainted error? {
http:Response response = new;
json reqPayload = {};
var payload = request.getJsonPayload();
// Try parsing the JSON payload from the request
if (payload is json) {
// Valid JSON payload
reqPayload = payload;
} else {
// NOT a valid JSON payload
response.statusCode = 400;
response.setJsonPayload({"Message":"Invalid payload - Not a valid JSON payload"});
var result = caller->respond(response);
handleError(result);
return;
}
json name = check reqPayload.Name;
json arrivalDate = check reqPayload.ArrivalDate;
json departDate = check reqPayload.DepartureDate;
json preferredType = check reqPayload.Preference;
// If payload parsing fails, send a "Bad Request" message as the response
if (name == () || arrivalDate == () || departDate == () || preferredType == ()) {
response.statusCode = 400;
response.setJsonPayload({"Message":"Bad Request - Invalid Payload"});
var result = caller->respond(response);
handleError(result);
return;
}
// Mock logic
// If request is for an available car type, send a rental successful status
string preferredTypeStr = preferredType.toString();
if (stringutils:equalsIgnoreCase(preferredTypeStr, AC) || stringutils:equalsIgnoreCase(preferredTypeStr, NORMAL)) {
response.setJsonPayload({"Status":"Success"});
}
else {
// If request is not for an available car type, send a rental failure status
response.setJsonPayload({"Status":"Failed"});
}
// Send the response
var result = caller->respond(response);
handleError(result);
}
}
function handleError(error? result) {
if (result is error) {
log:printError(result.reason(), err = result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment