How can I send a Conflict response with an Id in clojure - validation

I've defined a method where I'm simply checking where a job exists with a specific name and status, in case if job exists I want to send a conflict response but with an id
(defn insert-job [name status req]
(if (->> {:job-name name :status status}
db/insert-job
:amount
pos? )
(conflict) ; here I want to send a response as conflicts with a particular id as Long
(insert-job req)))
As in the below method I am able to produce a created response as Long
(defn insert-job [req]
(let [[errors job] (v/validate-job (:body req))]
(if errors
(unprocessable-entity {:errors errors})
(let [id (db/insert-job job)]
(created (format "/jobs/%d" id) {:id id})))))

ok. this would be as easy as
update your query to find the job id if exists
update your code to actually throw it.
in your hugsql queries file:
-- :name find-job-id :? :1
select id from job_history
where name = :name and status = :status
limit 1;
in your repo:
(defn insert-job [name status rec]
(if-let [id (some->> {:name name :status status}
(find-job-id db-spec)
:id)]
(ring.util.http-response/conflict!
{:message "record already exists"
:id id})
;; here do whatever you need for actual insertion
))
but ok. i would heavily advice you to read something on your chosen language and libraries.

Related

Puppet provider prefetch

I am writing a provider to generate self signed certificate using the certdog krestfield API.
I have implemented the create, destroy, exists? method and I can properly manage my certificate by making different call to the API.
I implemented puppet resource using the self.prefetch and self.instances methods. I can retrieve the properties of my resources to be aware of their current state.
My resource contain two sensitive types 'username' and 'password' who are required to make the API calls. I can't store those values on the filesystem and I want the 'puppet resource' command to ignore those types.
Currently when I run 'puppet apply' for the manifest:
certdog_certificate { 'tstpuppet':
ensure => present,
server => 'apiserver',
username => 'apiserver_username',
password => 'apiserver_password',
}
It returns:
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/username: defined 'username' as 'apiserver_username'
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/password: defined 'password' as 'apiserver_password'
Is there a way to hide sensitive types for puppet resources ? How should I process ?
I had to properly define my resource attributes.
The configurable data not part of the persistant state should be parameters as describe in the puppet documentation.
The attributes username and password are now define with newparam instead of newproperty as below.
module Puppet
Type.newtype(:certdog_certificate) do
#doc = 'Manage certificate using certdog REST API'
ensurable do
desc 'Create or remove a certificate'
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
defaultto :present
end
newparam(:cert_name, namevar: true) do
desc 'Name of the certificate request'
end
newparam(:username) do
desc 'Username for Certdog API server'
end
newparam(:password) do
desc 'Password for Certdog API server'
end
newproperty(:server) do
desc 'Certdog API server address'
end
end
#john-bollinger Thanks for your explanation, I was missing an important concept of the custom types.

How to access data within variable? Error: undefined method

Printing the contents of a variable gives me a bunch of data.
I want to access part of that data, but get an error.
I'm using Viewpoint::EWS and am successfully accessing the data I need.
calendaritems = folder.find_items({:folder_id => folder.folder_id, :calendar_view => {:start_date => sd.rfc3339(), :end_date => ed.rfc3339()}})
calendaritems.each do |event|
...
end
Printing the variable "event", I can see the data I need: "date_time_stamp" (or "appointment_reply_time").
#<Viewpoint::EWS::Types::CalendarItem:0x00005652b332dfa0
#ews_item=
:date_time_stamp=>{:text=>"2019-03-18T12:01:49Z"},
:appointment_reply_time=>{:text=>"2019-03-18T13:01:55+01:00"},
However, trying to access using "event.date_time_stamp" (or "event.appointment_reply_time") leads to the error
undefined method `date_time_stamp' for <Viewpoint::EWS::Types::CalendarItem:0x00005622f83c3d38> (NoMethodError)
Here's the code:
calendaritems = folder.find_items({:folder_id => folder.folder_id, :calendar_view => {:start_date => sd.rfc3339(), :end_date => ed.rfc3339()}})
calendaritems.each do |event|
if event.recurring?
puts "#{event.date_time_stamp} | #{(event.start-event.date_time_stamp).to_i} | #{event.organizer.email_address}"
if (event.start-event.date_time_stamp).to_i == reminderDays
executeSomething()
end
end
end
I'm looking through recurring appointments for a resource within a week. Since those will be silently dropped after a year, the plan is to set up a system to remind people that this will happen, so they can rebook the resource.
At first I tried using the creation date of the appointment (event.date_time_created), which works as expected, but then noticed, that people can update their appointments, thus resetting the 1 year timer.
That's why I also need the date of the last update.
The debug output you supplied says that event variable has an attribute "ews_item" and then it has a hash with an attribute "date_time_stamp", so try event.ews_item[:date_time_stamp]

How to get status code of successful response in handler in cljs-ajax?

I am successfully getting a response from an endpoint using cljs-ajax (as shown below). However, I cannot seem to differentiate between different success status codes in my response handler.
(ns mynamespace
(:require [ajax.core :as ajax]))
(defn start-monitoring []
(let [handler (fn [[ok response]]
(if ok
(.log js/console response)
(.error js/console (str response))))]
(ajax/ajax-request {:uri "/myendpoint"
:method :get
:params {:since (.getTime (js/Date.))}
:handler handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})})))
"ok" in the handler appears to simply be a true/false success flag, and does not differentiate between 200 and 204 status codes, both of which are considered successes. The response body is whatever text is returned in the response, and doesn't appear to contain a status code, unless the request failed.
How can I determine the status code of the response?
Seems like the response is a map with keys like :status which contains 200 for my test.
The rest of the keys are:
(:status :failure :response :status-text :original-text)
Use :response-format (ajax/ring-response-format).
See also: https://github.com/JulianBirch/cljs-ajax/issues/57

Parallel POST requests to DB with Ruby/DataMapper

I'am trying to implement kind of a matchmaking REST service for the game.
My matchmaking table is simple as
ID (Serial)
Client_Name_1 (String)
Client_Name_2 (String)
Basic idea is that when client sends me his "Name" I check if there is a row with Client_Name_2 = NULL and update this row.
If there is no "NULL" rows I create new row with Client_Name_1 as recieved client "Name"
Here is the router code:
post '/api/start' do
#parsing a request with client name
body = JSON.parse request.body.read
#checking if there is a row to update
t = Match.first(:Client_Name_2 => nil)
#matchmaking client to existing game if found
if t != nil
t.update(
Client_Name_2: body['name']
)
response = {:playerIs => '2', :id => t['id']}
#creating new game if nowhere to matchmake
elsif
m = Match.create(
Client_Name_1: body['name']
)
Task.create(
Match_ID: m['id']
)
response = {:playerIs => '1', :id => m['id']}
end
status 201
response.to_json
end
The tricky part for me is that when this router called simultaneously at the very same second from several different clients, all of these requests get the same row id from
#checking if there is a row to update
t = Match.first(:Client_Name_2 => nil)
and this code updates the same row for each request.
Is there a simple solution for this or i will have to implement something like queue to handle such simultaneous requests consequentially?
I will really appreciate your advice.

get data from http persistent connection

I tried for few days, I am a little confused here.
I am using clojure http-kit to make keepalive get request.
(ns weibo-collector.weibo
(:require [org.httpkit.client :as http]
[clojure.java.io :as io]))
(def sub-url "http://c.api.weibo.com/datapush/status?subid=10542")
(defn spit-to-file [content]
(spit "sample.data" content :append true))
#(http/get sub-url {:as :stream :keepalive 3000000}
(fn [{:keys [status headers body error opts]}]
(spit-to-file body)
))
I am pretty sure that I made a persistent connection to target server, but nothing written to sample.data file.
I tried as stream and as text.
I also tried ruby version the program create a persistent connection either, still nothing written.
So typically, the target will use webhook to notify my server new data is coming, but how to I get data from the persistent connection?
---EDIT---
require 'awesome_print'
url = "http://c.api.weibo.com/datapush/status?subid=10542"
require "httpclient"
c = HTTPClient.new
conn = c.get_async(url)
Thread.new do
res = conn.pop
while true
text = ""
while ch = res.content.read(1)
text = text+ch
break if text.end_with? "\r\n"
end
ap text
end
end
while true
end
Above is a working example using ruby, it uses a thread to read data from the connection. So I must miss something to get the data from clojure

Resources