<cfset apiResponse = {
success = true,
errors = [],
data = ""
} />
<cftry>
<cfparam name="form.image_id" type="numeric" />
<cfparam name="form.rating" type="numeric" />
<cfquery name="existingRating" datasource="#application.dsn#">
SELECT
r.id
FROM
rating r
WHERE
r.image_id = <cfqueryparam value="#form.image_id#" cfsqltype="cf_sql_integer" />
AND
r.ip_address = <cfqueryparam value="#cgi.remote_addr#" cfsqltype="cf_sql_varchar" />
AND
r.user_agent = <cfqueryparam value="#cgi.http_user_agent#" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfif existingRating.recordCount>
<cfset arrayAppend(
apiResponse.errors,
"You have already rated this image."
) />
</cfif>
<cfif NOT arrayLen( apiResponse.errors )>
<cfquery name="insertRating" datasource="#application.dsn#">
INSERT INTO rating
(
ip_address,
user_agent,
rating,
date_created,
image_id
) VALUES (
<cfqueryparam value="#cgi.remote_addr#" cfsqltype="cf_sql_varchar" />,
<cfqueryparam value="#cgi.http_user_agent#" cfsqltype="cf_sql_varchar" />,
<cfqueryparam value="#form.rating#" cfsqltype="cf_sql_integer" />,
<cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp" />,
<cfqueryparam value="#form.image_id#" cfsqltype="cf_sql_integer" />
);
SELECT
(
SUM( r.rating ) /
COUNT( r.rating )
) AS overall_rating
FROM
rating r
WHERE
r.image_id = <cfqueryparam value="#form.image_id#" cfsqltype="cf_sql_integer" />
;
</cfquery>
<cfset apiResponse.data = insertRating.overall_rating />
</cfif>
<cfcatch>
<cfset apiResponse.errors = [ cfcatch.message, cfcatch.detail ] />
</cfcatch>
</cftry>
<cfif arrayLen( apiResponse.errors )>
<cfset apiResponse.success = false />
</cfif>
<cfset jsonResponse = serializeJSON( apiResponse ) />
<cfset binaryResponse = toBinary( toBase64( jsonResponse ) ) />
<cfheader
name="content-length"
value="#arrayLen( binaryResponse )#"
/>
<cfcontent
type="text/x-json"
variable="#binaryResponse#"
/>