1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| program lzRestAPI;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
fphttpapp,
HTTPDefs,
httproute,
fpjson,
jsonparser,
mysql56conn,
SQLDB,
DB;
procedure catchallEndPoint(aRequest: TRequest; aResponse: TResponse);
begin
with aResponse do
begin
Content := 'This endpoint is not available.';
Code := 404;
ContentType := 'text/plain';
ContentLength := Length(Content);
SendContent;
end;
end;
procedure jsonResponse(var aResponse: TResponse; Data: string);
begin
with aResponse do
begin
Content := Data;
Code := 200;
ContentType := 'application/json';
ContentLength := Length(Content);
SendContent;
end;
end;
procedure jsonResponse404(var aResponse: TResponse);
begin
with aResponse do
begin
Content := 'This endpoint is not available.';
Code := 404;
ContentType := 'text/plain';
ContentLength := Length(Content);
SendContent;
end;
end;
procedure selectOneEndPoint(aRequest: TRequest; aResponse: TResponse);
const
cSQL: string =
'SELECT coOBJ, xxACT ' + 'FROM co WHERE coID=:coID LIMIT 1;';
var
jObject: TJSONObject;
lzConn: TMySQL56Connection;
lzTrans: TSQLTransaction;
lzQuery: TSQLQuery;
begin
lzConn := TMySQL56Connection.Create(nil);
lzQuery := TSQLQuery.Create(nil);
try
with lzConn do
begin
HostName := 'localhost';
Port := 3306;
UserName :='xxxxxxxxx';
Password := 'xxxxxxxxx';
DatabaseName := 'selzig';
Charset := 'utf8mb4';
end;
lzTrans := TSQLTransaction.Create(lzConn);
lzConn.Transaction := lzTrans;
lzQuery.Database := lzConn;
lzQuery.Transaction := lzTrans;
try
lzConn.Open;
with lzQuery do
begin
SQL.Text := cSQL;
Prepare;
Params.ParamByName('coID').AsString := aRequest.RouteParams['name'];
Open;
jObject := TJSONObject.Create;
try
if lzQuery.EOF then
jsonResponse404(aResponse)
else
begin
jObject.Strings['coID'] := aRequest.RouteParams['name'];
jObject.Strings['coOBJ'] := FieldByName('coOBJ').AsString;
jObject.Strings['xxACT'] := IntToStr(FieldByName('xxACT').AsInteger);
jsonResponse(aResponse, jObject.AsJSON);
end;
finally
jObject.Free;
end;
lzTrans.Commit;
lzQuery.Close;
end;
except
on e: ESQLDatabaseError do
begin
lzTrans.Rollback;
jsonResponse404(aResponse);
// Writeln('Erreur de connexion ou de Rollback à la base : ' +E.Message);
end;
end;
finally
lzConn.Free;
lzQuery.Free;
end;
end;
begin
Application.Port := 9090;
HttpRouter.RegisterRoute('/catchall', rmAll, @catchallEndPoint, True);
HttpRouter.RegisterRoute('/selectone/:name', rmGet, @selectOneEndPoint);
Application.Threaded := True;
Application.Initialize;
Writeln('Server is ready at localhost ' + IntToStr(Application.Port) + '.');
Application.Run;
end. |