Send ics blob through POST API - axios

I would like to generate an ics file then transform it in blob to finally send it through an Zendesk API POST call
The code
const blob = new Blob([icsContent], { type: "application/json" });
const uploadICSFile = await uploadZendeskFile('appointment.ics', blob);
axios POST
export async function uploadZendeskFile(filename: string, fileBlob: Blob): Promise<Upload> {
return await axios.post(
`https://${config.subdomain}.zendesk.com/api/v2/uploads.json?filename=${filename}`,
fileBlob,
{
auth: {
username: '*****',
password: '*****'
},
headers: {
'Content-Type': 'text/calendar',
}
}
);
}

The answer:
Typescript code:
const blob = new Blob([icsContent], { type: "application/octet-stream" });
const uploadICSFile = await uploadZendeskFile('appointment.ics', blob);

Related

upload and display images from cloudinary in nextjs + mongodb

(real estate nextjs application)
cannot send data with image URL to MongoDB and make a new property the API working Well,
and the MongoDB is connected i think the problem with the UI page i'm using formik for
form control , axios for API data fetching, cloudinary for images storing.
const [image, setImage] = useState([]);
const [property, setProperty] = useState(initialValues);
const { title, price, description, rentFrequency, rooms, baths, area, agency, purpose, furnishingStatus, amenities, city, garage, address, email, contact } = property;
console.log(property);
const handleOnChange = (e) => {
setProperty({ ...property, [e.target.name]: e.target.value });
};
const handleUploadInput = async (e) => {
const files = [...e.target.files];
const formData = new FormData();
for (let file of files) {
formData.append("file", file);
}
formData.append('upload_preset', 'my-uploads');
const res = await fetch(
"https://api.cloudinary.com/v1_1/shadow007/image/upload",
{
method: "POST",
body: formData,
}
);
const data = await res.json();
setImage([...image, data.secure_url]);
setProperty({ ...property, images: image }); // Maybe Im missing something around here
};
const handleOnSubmit = async (e) => {
e.preventDefault();
await createProperty();
};
// const validate = () => {
// if(!title || !price || !description || !content) return
// }
const createProperty = async () => {
try {
const res = await fetch("http://localhost:3000/api/properties", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(property),
});
const data = await res.json();
console.log(data);
} catch (err) {
console.log(err);
}

How to authorize to GitHub API using axios

How can I authorize to https://api.github.com using GitHub auth token and axios?
const axiosInstance = axios.create({
baseURL: 'https://api.github.com',
headers: {
Authorization: 'Bearer AUTH_TOKEN_HERE'
}
});
let response = await axiosInstance.get('/');
const fetchRepo = async () => {
const response = await axios.get(URL, {
method: "GET",
headers: {
'Authorization': 'token AUTH_TOKEN_HERE',
}
});
console.log(await response);
return response.data;
}

How to code Multipart-form POST REQUEST using apollo-datasource-rest

I want to code the multipart-form POST REQUEST below using apollo-datasource-rest
My attempt to code this leads to a BAD REQUEST error
const { RESTDataSource } = require('apollo-datasource-rest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
class SalesforceApi extends RESTDataSource {
constructor() {
super();
this.initialize({});
this.getAccessToken()
.then((accessToken) => {
this.headers = {
Authorization: `Bearer ${accessToken}`,
};
});
}
async getAccessToken() {
console.log('Getting Salesforce access token');
try {
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
{
username: 'FILTERED#FILTERED',
password: `${'FILTERED'}`,
grant_type: 'password',
client_id: 'FILTERED',
client_secret: 'FILTERED',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
const { accessToken } = response;
console.log(`ChangeGear sessionId: ${accessToken}`);
return accessToken;
} catch (error) {
console.log(`${error}`);
}
return 'No access token!!!';
}
module.exports = SalesforceApi;
[server:salesforce:local] POST https://test.salesforce.com/services/oauth2/token (343ms)
[server:salesforce:local] Error: 400: Bad Request
If memory serves correctly, form data is serialized slightly differently hence why the FormData interface exists. And the apollo-datasource-rest's this.post method is just a wrapper around fetch, so something like the below should work.
Instead of passing the body as a JSON object, try something like this
const formData = new FormData();
formData.append('username', 'FILTERED#FILTERED');
// ... more append lines for your data
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
formData
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);

How do I add body for PayPal partial refund to Axios?

I'm trying to post a partial refund to PayPal using Axios. If I use an empty object as the body I can complete a full refund. But I don't know how to add a body that will complete a partial refund. Here is my current code:
const axios = require('axios');
const qs = require('qs');
const refund = await axios.post("https://api-m.sandbox.paypal.com/v1/payments/capture/"
+ "myTransactionID" + "/refund",
qs.stringify({data:{amount:{currency_code:'USD',value:'20.00'}}}), //this works if I just use {};
{
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${ "myPayPalAccessToken" }`
},
});
console.log("refund: " + JSON.stringify(refund));
I get a "Request failed with status code 400" when I do this. I'm not sure if using a data object is necessary. Please help me figure out the syntax.
I figured it out. I should have been using application/json for the Content-Type. There was no need to stringify the body:
const axios = require('axios');
const qs = require('qs');
const PAYPAL_OAUTH_API = 'https://api.sandbox.paypal.com/v1/oauth2/token/';
const PAYPAL_PAYMENTS_API = 'https://api.sandbox.paypal.com/v2/payments/captures/';
const PayPalAuthorization = await axios({
method: 'POST',
url: PAYPAL_OAUTH_API,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
data: qs.stringify({
grant_type: 'client_credentials'
}),
auth: {
username: PAYPAL_CLIENT,
password: PAYPAL_SECRET
}
});
const PayPalToken = PayPalAuthorization.data.access_token;
const refund = await axios({
url: PAYPAL_PAYMENTS_API + "myTransactionID" + '/refund',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${ PayPalToken }`
},
data: {
amount: {
value: "10.99",
currency_code: "USD"
},
invoice_id: "INVOICE-123",
note_to_payer: "Defective product"
}
});
If you are posting an invoice_id don't forget to change the number for subsequent refunds.
Also check out these links:
https://developer.paypal.com/docs/checkout/integration-features/refunds/
https://developer.paypal.com/docs/api/payments/v2#captures_refund

Upload Image using Axios in React Native on Android

I'm trying to upload a file using axios and the request fails. have searched quite a bit seems like everyone is doing the same and works for them. Is there something I'm missing ?
My request in saga looks like this:
function* postUploadUtilityList(list) {
console.log('List', list.data);
const { data } = list;
for (const i in data) {
if (list.data.hasOwnProperty(i)) {
yield call(postUploadUtility, data[i]);
}
}
}
const createFormData = (photo, body) => {
const data = new FormData();
data.append('image', photo);
Object.keys(body).forEach((key) => {
data.append(key, body[key]);
});
return data;
};
function* postUploadUtility(item) {
console.log('item', item);
try {
const body = {
caption: 'utility',
};
const formData = createFormData(item, body);
const apiConfig = {
method: 'post',
baseURL: getBaseUrl(BB),
url: '/client/upload',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
const res = yield call(http, apiConfig);
if (res.status === 200) {
const { data } = res;
yield put({
type: POST_UTILITY_UPLOAD_SUCCESS,
data,
});
} else {
const { data } = res;
yield put({
type: POST_UTILITY_UPLOAD_FAILURE,
data,
});
}
} catch (e) {
yield put({
type: POST_UTILITY_UPLOAD_FAILURE,
e,
});
}
}
export default function* watchPostUploadUtility() {
yield takeLatest(POST_UTILITY_UPLOAD, postUploadUtilityList);
}
Log looks like as follow:
network call looks like as follow:
Try this solutions, Use image base64 instead of image url