Body parameters in POST request with capitals - ruby

I need to send a POST request with HTTParty, in which the body parameter must be shortDescription. Should I use:
payload = { :short_description => "Bla" }
or:
payload = { :shortDescription => "Bla" }
How can I do this?

Pass payload like this:
payload = { :shortDescription => "Bla" }
or:
payload = { "shortDescription" => "Bla" }

Related

how to get response from axios with multiable objects?

I am getting response payload from server like this:
{"0":
[
{"id":1,
"profile_id":"1",
"schoolName":"xx",
"courseName":"xx",
"courseDescription":null,
"created_at":"2020-06-25T09:11:21.000000Z",
"updated_at":"2020-06-25T09:11:21.000000Z"},
{"id":2,
"profile_id":"1",
"schoolName":"yy",
"courseName":"zz",
"courseDescription":"xx",
"created_at":null,
"updated_at":null}
],
"status":"Read Education info successfully!"}
Axios .then response is like this:
.then((response)=>{
vm.setState (
{ educations: Object.values(response.data) },
() => console.log(this.state.datas)
);
})
data- object has educations: []- array inside multiable
education: -objects
Q) how to pass axios response data payload to education object?,
export default {
data() {
return {
educations: [
education: {}],
--- Edit ---
Tried to get response like this:
.then((response)=>{
this.education = response.data.map(value => {
return {
schoolName: value.schoolName,
courseName: value.courseName
}
console.log('Receiving data ....')
})
Vue does not give any error, but I cannot see any data to pass data-object.
In Vuestools:
education : object
courseName: "" is empty.

Writing Structural Expectations with Jest

I am looking to write what I am calling structural expectations with Jest and I am not sure how this could be accomplished.
To start I have a graphql server and a database with a number of todo items. I currently have the following test that just returns true if the content within the database is the same as the response that I have written. I want to check instead that the response looks like an object with data that could be anything.
Here is the code that I have:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: "message",
id: "5bd9aec8406e0a2170e04494",
dateCreated: "1540992712052",
dateDue: "1111111111"
},
{
message: "message",
id: "5bd9aeec60a9b2579882a308",
dateCreated: "1540992748028",
dateDue: "1111111111"
},
{
message: "new message",
id: "5bd9af15922b27236c91837c",
dateCreated: "1540992789836",
dateDue: "1111111111"
}
]
}
})
});
});
Now I want to write something like this, where there can be any number of returned items and they follow similar structuring:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: expect.any(String),
id: expect.any(String),
dateCreated: expect.any(String),
dateDue: expect.any(String)
} // There needs to be unlimited additional items here
]
}
})
});
});
I have been looking throught the docs and I even tried nesting the expectations but I can't seem to get the desired response. Let me know what yo think or if I can clarify in any way.
I figured out the best way for me to do it. I would love to hear better answers. I wrote a function within the scope of the test as a jest.fn and then I called it. In that function, I made custom checks to parse the data that was received in the response. From there I added an expect function with the 'toHaveReturnedWith' method to see what the response of my custom function was and finishing out the test.
const addTodoResponse = jest.fn(() => {
// Custom parsing and check here
// Returns true or false
});
addTodoResponse();
expect(addTodoResponse).toHaveReturnedWith(true);
Are there better ways to do this out there?

Is it possible to add another field in the final response of GraphQL query?

I've been trying to research on how to add another root property of a GraphQL response but found nothing after 1 hour.
Normally, a GraphQL query looks like this:
{
myQuery() {
name
}
}
It responds with:
{
"data": {
"myQuery": []
}
}
I'm curious if I can add another root property in this response say "meta"
{
"data": {
"myQuery": []
},
"meta": {
"page": 1,
"count": 10,
"totalItems": 90
}
}
Is this possible, if not what's the best approach in tackling this with respect to GraphQL?
Thanks!
The apollo-server middleware can be configured with a number of configuration options, including a formatResponse function that allows you to modify the outgoing GraphQL response
const formatResponse = (response) => {
return {
meta
...response
}
}
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
formatResponse,
}));
You could pass the req object down to your context, mutate it within your resolver(s) and then use the result inside formatResponse. Something like...
app.use('/graphql', bodyParser.json(), (req, res, next) => graphqlExpress({
schema,
formatResponse: (gqlResponse) => ({
...gqlResponse
meta: req.metadata
}),
})(req, res, next));
Typically, though, you would want to include the metadata as part of your actual schema and have it included with the data. That will also allow you to potentially request multiple queries and get the metadata for all of them.
There's any number of ways to do that, depending on how your data is structured, but here's an example:
type Query {
getFoos: QueryResponse
getBars: QueryResponse
}
type QueryResponse {
results: [Result]
meta: MetaData
}
union Result = Bar | Foo
You can add anything in the response as well... Please follow below code.
app.use('/graphql', bodyParser.json(), graphqlExpress(req => {
return {
schema: tpSchemaNew,
context: {
dbModel
},
formatError: err => {
if (err.originalError && err.originalError.error_message) {
err.message = err.originalError.error_message;
}
return err;
},
formatResponse : res => {
res['meta'] = 'Hey';
return res;
}
}
}))
Apollo Server-specific:
Just adding to the previous answers that formatResponse() has another useful argument, requestContext.
If you are interested in extracting values from that (for example, the context passed to the resolver), you can do the following. BEWARE HOWEVER, the context will likely contain sensitive data that is supposed to be private. You may be leaking authentication data and secrets if not careful.
const server = new ApolloServer({
schema,
formatResponse: (response, requestContext) => {
//return response
const userId = requestContext.context.user.id
response = Object.assign(response, {
extensions: {
meta: {
userId: userId
}
}
}
return response
},
})
The above will return something like this in the gql query response (note the extensions object):
{
data: {
user: {
firstName: 'Hello',
lastName: 'World'
}
},
extensions: { // <= in Typescript, there is no `meta` in GraphQLResponse, but you can use extensions
meta: {
userId: 1234 //<= data from the context
}
}
}
The full list of properties available in requestContext:
at node_modules/apollo-server-types/src/index.ts>GraphQLRequestContext
export interface GraphQLRequestContext<TContext = Record<string, any>> {
readonly request: GraphQLRequest;
readonly response?: GraphQLResponse;
readonly context: TContext;
readonly cache: KeyValueCache;
// This will be replaced with the `operationID`.
readonly queryHash?: string;
readonly document?: DocumentNode;
readonly source?: string;
// `operationName` is set based on the operation AST, so it is defined even if
// no `request.operationName` was passed in. It will be set to `null` for an
// anonymous operation, or if `requestName.operationName` was passed in but
// doesn't resolve to an operation in the document.
readonly operationName?: string | null;
readonly operation?: OperationDefinitionNode;
/**
* Unformatted errors which have occurred during the request. Note that these
* are present earlier in the request pipeline and differ from **formatted**
* errors which are the result of running the user-configurable `formatError`
* transformation function over specific errors.
*/
readonly errors?: ReadonlyArray<GraphQLError>;
readonly metrics?: GraphQLRequestMetrics;
debug?: boolean;
}

How to pass the Query Data in Body for making REST API call in graphql

I am doing a post operation where i am getting some response.
My URl looks Like:
http://domainname/api/v1:id
As a part of body i want to pass the below data:
{ elemetnt { id, name } }
Can anybody suggest me how i can achieve this.
i am trying with the below code but i am getting 404:
let queryParam = `{ elemetnt { id, name } }`;
this.http.post(`http://domainname/api/v1:1`, {
query: queryParam,
}, {
headers: new Headers({
'Content-Type': 'application/graphql',
}),
})
.catch((error: Response | any) => {
console.log(error);
return Observable.of(error);
})
.subscribe((res) => {
console.log(JSON.stringify(res));
});
I know i am doing something wrong. But, if somebody can help me on this then it would be great help.
It depends on method which receiving this data, but this is correct format for you as given in question
queryParam= { element : { id: "0000" , name: "name" };
you may need to stringy your solution
Canyou please try with
'Content-Type': 'application/json'
and pass json body like
{"query":"{ elemetnt { id, name } }" }
I think this may help you

Slack API Postmessage

I'm looking at the Slack API for use in teaching API Consumption in Ruby. Does the Slack API require all the parameters as part of the query string or can it take post-Params as well.
Messages like this work:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}" + "&text=#{msg}&channel=#{channel}"
data = HTTParty.post(url)
end
However this does not:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}"
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}"
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
end
I think the cleanest answer is just this:
url = 'https://someslackwebhookurl/adfdsf/sdfsfsd'
msg = 'We are fumanchu'
HTTParty.post(url, body: {"text":"#{msg}"}.to_json)
I have managed to answer the question with:
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}",
"username" => bot_name,
"icon_url" => icon_url,
"as_user" => "false"
},
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' })
It won't work with JSON content oddly enough.

Resources