Write, Bureaucrats, Administrators
4,332
edits
mNo edit summary |
mNo edit summary |
||
Line 308: | Line 308: | ||
</source> | </source> | ||
== | == Processing an HTTP request == | ||
Scripts can send HTTP requests to Web services through their APIs. | |||
Processing for HTTP requests allows integration between Memento and the system. All file operations use the Http object, which works through global method http(). | |||
HTTP requests must fulfill two requirements: | |||
# Script execution should be asynchronous, because processing of the request on the network can take a long time. Therefore, HTTP requests of the last Event phase. | |||
# The library should have permission - Network. | |||
=== Object Http === | === Object Http === | ||
Interface for processing HTTP requests. | |||
==== | ==== Methods ==== | ||
=====get(url)===== | ===== get(url) ===== | ||
: | :Execute get request | ||
: | :Argument: url - HTTP address, starting with http or https | ||
: | :Result: HttpResult - Object containing the result of the execution of the HTTP request. | ||
=== Object HttpResult === | === Object HttpResult === | ||
Result of the execution of the HTTP request | |||
==== | ==== Properties ==== | ||
;code : | ;code : HTTP code of the response, if the request is successful (usually is 200). | ||
;body : | ;body : The response in text form | ||
=== Examples === | |||
==== Currency Conversion ==== | |||
Suppose the library contains two fields: PriceUSD and PriceEUR. | |||
The user will enter the value in PriceUSD and the value in Euros will appear in PriceEUR according to the current exchange rate. | |||
We will create a Trigger on Event '''Create Entry to Add''' and phaase '''After Saving Entry'''. | |||
<source lang="javascript" line> | <source lang="javascript" line> | ||
result = http().get("http://api.fixer.io/latest?base=USD") | result = http().get("http://api.fixer.io/latest?base=USD") // Use service http://fixer.io/ to get conversion rate in JSON format | ||
usdToEur = JSON.parse(result.body)["rates"]["Eur"] | usdToEur = JSON.parse(result.body)["rates"]["Eur"] // Use standard JavaScript object JSON to parse the result | ||
entry().set("PriceEUR" , entry().field( "PriceUSD") * usdToEur ) | entry().set("PriceEUR" , entry().field( "PriceUSD") * usdToEur ) // Multiply PriceUSD by the conversion rate to determine the value for PriceEUR | ||
</source> | </source> | ||
==== | ==== Creating a Task in the Todoist App ==== | ||
[https://todoist.com Todoist] — | [https://todoist.com Todoist] — A Web service and mobile app for task management. Todoist allows task creation via API [https://developer.todoist.com/]. | ||
In the following example of task creation, text will be taken from the Memento library entry. | |||
<source lang="javascript" line> | <source lang="javascript" line> | ||
var commands='[{"uuid":"' + guid() + '","temp_id":"' + guid() + '","type":"item_add","args":{"content":"' + entry().field("Task") + '"}}]' | var commands='[{"uuid":"' + guid() + '","temp_id":"' + guid() + '","type":"item_add","args":{"content":"' + entry().field("Task") + '"}}]' | ||
Line 350: | Line 351: | ||
if (result.code == 200) message('Task has been successfully created") | if (result.code == 200) message('Task has been successfully created") | ||
</source> | </source> | ||
#Составляем команду в json формате для создания задачи в todoist, формат команды описан здесь: https://developer.todoist.com/#add-an-item. В команде должны присутствовать уникальные идентификаторы, для их получения используем глобальную функцию guid(). | #Составляем команду в json формате для создания задачи в todoist, формат команды описан здесь: https://developer.todoist.com/#add-an-item. В команде должны присутствовать уникальные идентификаторы, для их получения используем глобальную функцию guid(). | ||
#Выполняем http запрос. Атрибут token используется для авторизации в todoist, его можно получить в Настройках Todoist вкладка Аккаунт. Так как текст задачи может содержать символы недопустимые в URL-запроса, то экранируем их с помощью стандартной функции encodeURIComponent(). | #Выполняем http запрос. Атрибут token используется для авторизации в todoist, его можно получить в Настройках Todoist вкладка Аккаунт. Так как текст задачи может содержать символы недопустимые в URL-запроса, то экранируем их с помощью стандартной функции encodeURIComponent(). |