| 1 |
|
-module(shurbej_http_schema). |
| 2 |
|
-export([init/2]). |
| 3 |
|
|
| 4 |
|
%% GET /schema — serve the bundled Zotero schema from priv/schema.json. |
| 5 |
|
%% The bytes are cached in persistent_term (set-once, read-many — the ideal |
| 6 |
|
%% use) so we don't hit the disk on every poll. |
| 7 |
|
init(Req0, State) -> |
| 8 |
2 |
case cowboy_req:method(Req0) of |
| 9 |
|
<<"GET">> -> |
| 10 |
1 |
case schema_bytes() of |
| 11 |
|
{ok, SchemaJson} -> |
| 12 |
1 |
Req = cowboy_req:reply(200, #{ |
| 13 |
|
<<"content-type">> => <<"application/json">> |
| 14 |
|
}, SchemaJson, Req0), |
| 15 |
1 |
{ok, Req, State}; |
| 16 |
|
{error, _} -> |
| 17 |
:-( |
Req = shurbej_http_common:error_response(500, |
| 18 |
|
<<"Schema file not found">>, Req0), |
| 19 |
:-( |
{ok, Req, State} |
| 20 |
|
end; |
| 21 |
|
_ -> |
| 22 |
1 |
Req = shurbej_http_common:error_response(405, <<"Method not allowed">>, Req0), |
| 23 |
1 |
{ok, Req, State} |
| 24 |
|
end. |
| 25 |
|
|
| 26 |
|
schema_bytes() -> |
| 27 |
1 |
case persistent_term:get({?MODULE, schema}, undefined) of |
| 28 |
|
undefined -> |
| 29 |
1 |
case file:read_file(schema_path()) of |
| 30 |
|
{ok, Bin} -> |
| 31 |
1 |
persistent_term:put({?MODULE, schema}, Bin), |
| 32 |
1 |
{ok, Bin}; |
| 33 |
|
{error, _} = Err -> |
| 34 |
:-( |
Err |
| 35 |
|
end; |
| 36 |
|
Bin -> |
| 37 |
:-( |
{ok, Bin} |
| 38 |
|
end. |
| 39 |
|
|
| 40 |
|
schema_path() -> |
| 41 |
1 |
PrivDir = code:priv_dir(shurbej_web), |
| 42 |
1 |
filename:join(PrivDir, "schema.json"). |