cloudconvert API NOT working with netlify Serverless function - netlify-function

I was using cloudconvert api from node JS, which was working fine when I hosted in heroku. But when I made netlify serverless function it is returning error. Is it because serverless function exits before completing the task?
try {
let job = await cloudConvert.jobs.create({
tasks: {
'const-1': {
operation: 'const/raw',
// file: file_string_output,
file: '<div>Welcome ... testing...</div>',
filename: `${fileName}.html`,
},
'task-1': {
operation: 'convert',
input_format: 'html',
output_format: 'pdf',
engine: 'chrome',
input: ['const-1'],
zoom: 1,
print_background: true,
display_header_footer: false,
wait_until: 'load',
wait_time: 0,
},
'export-1': {
operation: 'export/s3',
input: ['task-1'],
bucket: process.env.S3_BUCKET_NAME,
region: process.env.S3_BUCKET_REGION,
access_key_id: process.env.S3_ACCESS_KEY,
secret_access_key: process.env.S3_ACCESS_SECRETE,
key: `${process.env.S3_BUCKET_FOLDER}/${fileName}.pdf`,
},
},
})
cloudConvert.jobs.subscribeEvent(job.id, 'finished', (event) => {
console.log('cloud convert stages finished', event.job)
})
cloudConvert.jobs.subscribeEvent(job.id, 'error', (event) => {
console.log('error', event.job)
})
cloudConvert.jobs.subscribeTaskEvent(job.id, 'finished', async (event) => {
console.log('cloud convert Task stages finished', event.job)
})
cloudConvert.jobs.subscribeTaskEvent(job.id, 'error', (event) => {
console.log('Task on error', event.task)
})
} catch (error) {
console.log(' Cloud convert key is invalid??:', error)
}

I have figured out the problem. In below code, there was a typo.
operation: 'const/raw', ==>>>> operation: 'import/raw'
It was my bad. Since the netlify serverless did not support Es6, I have to change all import syntax to require() syntax and I had a global search and replace import==> const which effected here as well. So silly me...
'const-1': {
operation: 'const/raw', ==>>>>
// file: file_string_output,
file: '<div>Welcome ... testing...</div>',
filename: `${fileName}.html`,
},

Related

How to recover SIP js Invitation Object or Session Object in React Js on page refresh

I am implementing Audio/Video call with SIP js and Astrisk server in React JS.I was successful on creating the WebRTC Audio/Video calling. But I am facing an issue with storing the Invitation or Session Object for SIP js. Because Circular JSON data can't be stringed to store.
Assume someone has started calling and the other end got notification of calling and in that case if the page refreshed or reloaded I am unable to recover the call session to take any action(answer/ decline)
/**
* The following code is inside useState and the dependency are handled properly.
* For making it simple and sort I have just copied the required parts. */
const simpleUserDelegate = {
onCallAnswered: (session) => {
console.log(` Call answered`);
if (simpleUser) {
let remoteVideoTrack = simpleUser.getRemoteVideoTrack(session);
if (remoteVideoTrack) {
} else {
setIsAudioCall(true);
}
}
setIsCallAnswered(true);
setIsCallRecieved(false);
localStorage.setItem('isCallRecieved',null);
localStorage.setItem('callerName',null);
localStorage.setItem('callerImage',null);
setIsCallling(false);
},
onCallCreated: (session) => {
setCallSession(session);
console.log(session,` Call created`);
//console.log('session====>',JSON.stringify(session))
// localStorage.setItem('callerUserAgent',JSON.stringify(session._userAgent));
setIsCallling(true);
localStorage.getItem('callerUserAgent')
},
onCallReceived: (invitation) => {
console.log('invitation',invitation);
console.log('invitationSession',invitation.session);
setCallerActiveRoom(invitation._userAgent.options.displayRoomId);
setCallerName(invitation._userAgent.options.displayName);
setCallerImage(invitation._userAgent.options.displayImage);
localStorage.setItem('callerUserAgent',JSON.stringify(invitation.request));
console.log(` Call received`);
// dispatch(setActiveRoomId(invitation._userAgent.options.displayRoomId));
setIsCallRecieved(true);
localStorage.setItem('isCallRecieved',true);
localStorage.setItem('callerName',invitation._userAgent.options.displayName);
localStorage.setItem('callerImage',invitation._userAgent.options.displayImage);
},
onCallHangup: () => {
console.log(` Call hangup`);
setIsCallling(false);
setIsCallRecieved(false);
localStorage.setItem('isCallRecieved',null);
localStorage.setItem('callerName',null);
localStorage.setItem('callerImage',null);
setIsCallAnswered(false);
},
onCallHold: () => {
console.log(` Call hold`);
},
onRegistered: () => {
//console.log('session',session);
console.log(` Call registered`);
},
onUnregistered: () => {
console.log(` Call unregistered`);
},
onServerConnect: () => {
console.log(` server connect`);
},
onServerDisconnect: () => {
console.log(` server dis connect`);
}
};
let simpleUserOptions = {
// traceSip: false,
// logBuiltinEnabled: false,
delegate: simpleUserDelegate,
media: {
constraints: {
audio: true,
video: true
},
local: {
video: document.getElementById('localMedia')
},
remote: {
video: document.getElementById('remoteMedia'),
//audio: remoteAudioRef.current
}
},
userAgentOptions: {
logBuiltinEnabled: true,
logLevel: "debug",
authorizationPassword: password,
authorizationUsername: username,
uri: urI,
noAnswerTimeout : 30,
displayName: name,
displayImage: profileImage,
displayRoomId: `hi${displayRoomId}`
},
};
const simpleUserObj = new Web.SessionManager('wss://pbx.scinner.com:8089/ws', simpleUserOptions);
if(!simpleUserObj.isConnected()){
simpleUserObj
.connect()
.then(() => {
console.log(`${user.username} connected`);
simpleUserObj.register().then(() => {
console.log(`${user.username} registerd`);
}).catch((error) => {
alert("Failed to register.\n" + error);
});
})
.catch((error) => {
alert("Failed to connect.\n" + error);
});
setIsSARegistered(true);
setSimpleUser(simpleUserObj);
setCallerUserAgent
}else{
console.log('isconnected');
setIsSARegistered(true);
}
/**
Set calling
*/
const setCalling = (name, target) => {
simpleUser
.call(target, {
sessionDescriptionHandlerOptions: {
constraints: {
audio: true,
video: true
}
},
inviteWithoutSdp: false
}).then(() => {
console.log(`anon placed a call`);
}).catch((error) => {
console.error(`[${simpleUser.id}] failed to place call`);
console.error(error);
alert("Failed to place call.\n" + error);
});
//setIsCallling(true);
// console.log('isCallling', isCallling)
}
}
const answerCall = () => {
//callSession stored in local state
if (callSession) {
simpleUser.answer(callSession).then(() => {
console.log(`call answered`);
}).catch((error) => {
console.error(`call answered failed`);
console.error(error);
// alert("Failed to place call.\n" + error);
});
}
};

Axios Spy not being called correct number of times in Jest

I have a React context I am testing that runs a single function to check for an application update. The checkForUpdate function looks like this:
async function checkForUpdate() {
if (isPlatform('capacitor')) {
const maintanenceURL =
'https://example.com/maintenance.json';
const updateURL =
'https://example.com/update.json';
try {
const maintanenceFetch: AxiosResponse<MaintanenceDataInterface> =
await axios.get(maintanenceURL);
console.log('maintain', maintanenceFetch);
if (maintanenceFetch.data.enabled) {
setUpdateMessage(maintanenceFetch.data.msg);
return;
}
const updateFetch: AxiosResponse<UpdateDataInterface> = await axios.get(
updateURL
);
console.log('updateFetch', updateFetch);
if (updateFetch.data.enabled) {
const capApp = await App.getInfo();
const capAppVersion = capApp.version;
console.log('Thi is a thinkg', capAppVersion);
if (isPlatform('android')) {
console.log('hi');
const { currentAndroid, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentAndroid.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
} else {
const { currentIos, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentIos.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
}
}
} catch (err) {
console.log('Error in checkForUpdate', err);
}
}
}
For some reason, in my test I wrote to test this, my axiosSpy only shows that it has been called 1 time instead of the expected 2 times. The console logs I posted for both get requests run as well. I cannot figure out what I am doing wrong.
Here is the test:
it.only('should render the update page if the fetch call to update bucket is enabled and returns a different major version', async () => {
const isPlatformSpy = jest.spyOn(ionicReact, 'isPlatform');
isPlatformSpy.mockReturnValueOnce(true).mockReturnValueOnce(true);
const appSpy = jest.spyOn(App, 'getInfo');
appSpy.mockResolvedValueOnce({
version: '0.8.0',
name: 'test',
build: '123',
id: 'r132-132',
});
const axiosSpy = jest.spyOn(axios, 'get');
axiosSpy
.mockResolvedValueOnce({
data: {
enabled: false,
msg: {
title: 'App maintenance',
msg: 'We are currently solving an issue where users cannot open the app. This should be solved by end of day 12/31/2022! Thank you for your patience 😁',
btn: 'Ok',
type: 'maintenance',
},
},
})
.mockResolvedValueOnce({
data: {
current: '1.0.0',
currentAndroid: '1.0.0',
currentIos: '2.0.0',
enabled: true,
majorMsg: {
title: 'Important App update',
msg: 'Please update your app to the latest version to continue using it. If you are on iPhone, go to the app store and search MO Gas Tax Back to update your app. The button below does not work but will in the current update!',
btn: 'Download',
type: 'major',
},
minorMsg: {
title: 'App update available',
msg: "There's a new version available, would you like to get it now?",
btn: 'Download',
type: 'minor',
},
},
});
customRender(<UpdateChild />);
expect(axiosSpy).toHaveBeenCalledTimes(2);
});

xstate pass event data into onDone from service

I have xstate react script whereby a user fills in a form, and presses submit. On submit the xstate received a send("VALIDATE", {formData}) and that is run through a service that validates the form. On success the script transitions to the target: "success" and i need that final "success" state to call an external function which actually does the saving of the script.
I can get the data into the validator function, BUT, after the onDone, the subsequent success state doesn't appear to see the data.
How can I wire the data from the validating event to the success event??
id: 'validator',
initial: 'populating',
context: {},
states: {
populating: {
on: {
VALIDATE: 'validating'
}
},
validating: {
invoke: {
src: (context, data) => doValidate(data),
onDone: {
target: 'success',
actions: assign({ data: "hello world"})
},
onError: 'failure'
}
},
success: {
invoke: {
// I do see the hello world here, but what I want is the 'data' from the doValidate(data)
src: (ctx)=>{console.log("invoked success, what can I see here: ", ctx)}
}
},
I'm triggering the validate via: send("VALIDATE", formData)
If I understood you correctly you want the event from the first service onDoneto be available to the second service?
The easiest way would be to put the data on the context and access it in the other state/service and delete it afterward.
Or you can model your machine to send custom event to itself when the first
service is done.
import { createMachine, assign, send, interpret } from "xstate";
const machine = createMachine({
preserveActionOrder: true, //make sure actions are executed in order
id: "validator",
initial: "populating",
context: {},
states: {
populating: {
on: {
VALIDATE: "validating"
}
},
validating: {
on: {
// Listen to the event that fires when the first service is done
FIRST_SERVICE_DONE: {
target: "success"
}
},
invoke: {
src: (context, data) => Promise.resolve({ prop: "first service" }),
onDone: {
// target: 'success',
actions: [
assign({ data: "hello world" }),
//instead of using target:'success' send a custom
//event that has access to the data from the service
send((context, event) => {
//event here has event.data.prop === 'first service'
console.log("send evt ", event);
return {
type: "FIRST_SERVICE_DONE",
prop: event.data.prop
};
})
]
},
onError: "failure"
}
},
success: {
invoke: {
src: (_ctx, evt) => {
console.log("evt ", evt.prop); //first service
}
}
},
failure: {}
}
});
const service = interpret(machine);
service.start();
service.send({ type: "VALIDATE" });
Codesandbox
In Xstate the context is the extended state, so it doesn't seem like a good practice to use the context as a "machine memory". The extended state is used so that you don't have a potentially infinite number of states.
In case you need to preserve information that is sent by the event going to the state that invokes a Promise, you can add that information to the response. For example:
export const myMachineServices = {
myRequest: (context, event) =>
new Promise(resolve => {
setTimeout(() => {
resolve({
payload: 'some data',
})
}, 1000)
}).then(res => ({
...res,
event.data
}))
.catch(err => ({
...err,
event.data
})),
}

ReactNative Expo Preloading & Caching Images

I'm new to react-native im trying to preload 10 images at the start of the app I followed expo documentation but
I want to cache images from an external file but it gives me an error [Un Handeled Promise Rejection]
here is my entries.js
export const ENTRIES1 = [
{
title: 'Makeup Artists',
illustration: require('../assets/img/makeup.png')
},
{
title: 'Photographers',
illustration: require('../assets/img/Photographers.png')
},
{
title: 'Wedding Planners',
illustration: require('../assets/img/weddingPlanner.jpg')
},
{
title: 'Wedding Halls',
illustration: require('../assets/img/wedding-Hall.png')
},
{
title: 'Laser & Beauty Centers',
illustration: require('../assets/img/laser.png')
},
]
loadingScreen.js
async componentDidMount() { //Preload Fonts
await Asset.loadAsync(ENTRIES1.illustration),
await Font.loadAsync({
'Roboto': require('../../node_modules/native-base/Fonts/Roboto.ttf'),
'Roboto_medium': require('../../node_modules/native-base/Fonts/Roboto_medium.ttf'),
...Ionicons.font,
});
this.checkIfLoggedIn();
}
what am i doing wrong ? Thanks
Try this :)
function cacheImages(images) {
return images.map(image => {
if (typeof image.illustration === 'string') {
return Image.prefetch(image.illustration);
} else {
return Asset.fromModule(image.illustration).downloadAsync();
}
});
}
async componentDidMount() {
await Asset.cacheImages(ENTRIES1),
await Font.loadAsync({
'Roboto': require('../../node_modules/native-base/Fonts/Roboto.ttf'),
'Roboto_medium': require('../../node_modules/native-base/Fonts/Roboto_medium.ttf'),
...Ionicons.font,
});
this.checkIfLoggedIn();
}

dependency on a single test suit causes other test suits to fail - Jest

I am mocking the following library on one of my test suits:
it's react-native-awesome-card.io:
jest.mock('react-native-awesome-card-io', () => {
return {
CardIOUtilities: {
preload: jest.fn(() => Promise.resolve('the response')),
},
}
})
describe('PaymentDetails', () => {
test('snapshot = PaymentDetails not empty', () => {
const options = {
navigation: {
state: {
params: {
paymentMethod: {
accountName: 'Test Account',
expMonth: 11,
expYear: 2021,
number: '4111111111111111',
type: 'Visa',
preferred: true,
},
},
},
},
getUserInfo: { locale: 'en-US' },
}
snapshot(shallow(<PaymentDetails {...options} />))
})
This seems to work fine for this test but I notice my other test suits start failing with errors like these:
It seems they all need that library mocked on them as well. But why?
And what is the solution to this? I hate replication mock code on each one of them.

Resources