generated from intersystems-community/objectscript-docker-template
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Base.cls
110 lines (94 loc) · 2.75 KB
/
Base.cls
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
Class Sample.REST.Base Extends %CSP.REST [ System = 3 ]
{
Parameter CHARSET = "utf-8";
Parameter CONTENTTYPE = "application/json";
Parameter HandleCorsRequest = 1;
Parameter PAGESIZE As INTEGER = 20;
ClassMethod OnPreDispatch(pUrl As %String, pMethod As %String, ByRef pContinue As %Boolean) As %Status
{
SET tSC = $$$OK
TRY {
// Set the return type according to the Accept type in the request. Default is application/json.
IF ('..AcceptsContentType(..#CONTENTTYPEJSON)) {
SET tSC = ..ReportHttpStatusCode(..#HTTP406NOTACCEPTABLE), pContinue=0
QUIT
} ELSE {
// This always returns json
SET %response.ContentType=..#CONTENTTYPEJSON
}
// read request object into %DynamicObject format
IF ((pMethod'="POST") && (pMethod'="PUT")) || (%request.Content="") {
SET %request.Content = {}
} ELSE {
IF '$isobject(%request.Content) {
SET tContent = %request.Content
} ELSE {
SET tContent = ""
WHILE '%request.Content.AtEnd {
SET tContent = tContent_%request.Content.Read()
}
}
IF (tContent="") {
SET %request.Content = {}
} ELSE {
SET tContent = $zconvert(tContent, "I", "UTF8")
SET %request.Content = ##class(%Library.DynamicObject).%FromJSON(tContent)
}
}
} CATCH ex {
SET tSC = ex.AsStatus()
}
QUIT ##class(%iKnow.REST.Base).%ErrorHandler(tSC, .pContinue)
}
ClassMethod %ProcessResult(pStatus As %Status = {$$$OK}, pResult As %DynamicObject = "") As %Status [ Internal ]
{
#dim %response As %CSP.Response
SET tSC = $$$OK
IF $$$ISERR(pStatus) {
SET %response.Status = 500
SET tSC = ..StatusToJSON(pStatus, .tJSON)
IF $isobject(tJSON) {
SET pResult = tJSON
} ELSE {
SET pResult = { "errors": [ { "error": "Unknown error parsing status code" } ] }
}
}
ELSEIF pStatus=1 {
IF '$isobject(pResult){
SET pResult = {
}
}
}
ELSE {
SET %response.Status = pStatus
SET error = $PIECE(pStatus, " ", 2, *)
SET pResult = {
"error": (error)
}
}
IF pResult.%Extends("%Library.DynamicAbstractObject") {
WRITE pResult.%ToJSON()
}
ELSEIF pResult.%Extends("%JSON.Adaptor") {
DO pResult.%JSONExport()
}
ELSEIF pResult.%Extends("%Stream.Object") {
DO pResult.OutputToDevice()
}
QUIT tSC
}
ClassMethod ReportHttpStatusCode(pHttpStatus, pSC As %Status = {$$$OK}) As %Status
{
Set %response.Status=pHttpStatus
If $$$ISERR(pSC) Do ..outputStatus(pSC)
/*
If (+pHttpStatus>=400) {
Set %response.ContentType = "application/json"
SET pResult = {
"error": ($PIECE(pHttpStatus, " ", 2, *))
}
Return ..%ProcessResult($$$OK, pResult)
}*/
Return $$$OK
}
}