firebase function deploy fail, but logs are confusing - node.js

firebase function deploy fail, but logs are confusing. Actually, logs does not provide useful info.
I have tried renaming the functions 3 times, but no luck. This is annoying.
/**
* Get random number
* #param {number} min
* #param {number} max
* #return {number} random
*/
function between(min, max) {
return Math.floor(
Math.random() * (max - min) + min
);
}
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid, authToken);
exports.sendSMS2=functions.pubsub.schedule("46 7 * * *")
.timeZone("America/New_York").onRun((context) =>{
return client.messages
.create({body: text +" " +between(1, 10), from: from, to: to})
.then((message) => console.log(message.sid));
});
console:
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint .
Functions deploy had errors with the following functions:
sendSMS2(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions

Related

Why custom services do not work on cron jobs in strapi.io

I created a cron job and use Strapi custom service that I wrote. But an error comes as: TypeError: Cannot read property 'services' of undefined at Job.1 * * * * * [as job] .
Here is my cron job code:
module.exports = {
'1 * * * * *': ({ strapi }) => {
strapi.services.account.myService();
},
};
I'm using strapi version 3.6.8.
The answer to this question is simple. You're using the syntax from StrapiV4 in StrapiV3. The correct syntax for cronjob in strapiv3 is as follows:
module.exports = {
/**
* Simple example.
* Every monday at 1am.
*/
'0 0 1 * * 1': () => {
// you can then reference you strapi custom service like so
await strapi.services.account.myServiceMethod();
},
};
References
Cron Jobs in Strapi V4
Cron Job in Strapi V3

NPM cronJob - dynamically set time

here is my code for scheduling a task. i have used separate routes for starting,stopping and changing the time as given below. please tell me if its correct. and also im getting an error for changing the time frequency.please help me.
const cronjob=require('cron').CronJob
var first='* * * * * *'
var task=function() {
console.log('last'+job.lastDate()+' next '+job.nextDates(1));
}
var complete=function(){
console.log('the end.........')
}
var job = new cronjob(first,task, complete, false, 'Asia/Kolkata');
app.get('/start',(req,res)=>{
job.start()
console.log('is job running? ', job.running);
res.send('cron started')
})
app.get('/set',(req,res)=>{
var time=req.headers.time /* input taken from user for changing the frequency*/
time='30 5 1-31 0-11 1-7' /*hard-coded temporary for testing*/
console.log(time)
job.setTime(time)
})
/set api is throwing an error
/Error: time must be an instance of CronTime./
we have to use instance of a cronTime i.e.
const CronTime = require('cron').CronTime
.
.
.
var time=req.query.time
//time='*/5 * * * * *'
job.setTime(new CronTime(time))
res.send('time changes')

gRPC: 14 UNAVAILABLE: failed to connect to all addresses

grpc fails to connect even when I set my jest test() async function to a 100000ms cap before it times out.
// terminal, after running jest --watch
● creates new record
14 UNAVAILABLE: failed to connect to all addresses
at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 skipped, 2 total
Snapshots: 0 total
Time: 106.03s, estimated 116s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
owner#G700:~/PhpstormProjects/shopify/bu
FAIL functions/src/classes/__tests__/FirestoreConnection.test.ts (108.991s)
✕ creates new record (100029ms)
○ skipped
● creates new record
: Timeout - Async callback was not invoked within the 100000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 100000ms timeout specified by jest.setTimeout.Error:
51 |
52 |
> 53 | test("creates new record", async () => {
| ^
54 | const addedDocument = await db
55 | .createNew(RecordTypes.globalRule, {
56 | storeId : "dummyStoreId"
at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
at Object.<anonymous> (functions/src/classes/__tests__/FirestoreConnection.test.ts:53:1)
● creates new record
14 UNAVAILABLE: failed to connect to all addresses
at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 skipped, 2 total
Snapshots: 0 total
Time: 111.16s
Ran all test suites related to changed files.
// FirebaseConnection.ts, inside the class
protected async addDocument(collectionName: string, documentData: object): Promise<firestore.DocumentSnapshot|null> {
try {
const newlyAddedDocument = await this.database
.collection(collectionName)
.add(documentData);
return await newlyAddedDocument.get();
}
catch (e) {
console.log(e, `=====error=====`);
return null;
}
}
// --------------- Public Methods
public async createNew(type: RecordTypes, documentData: object): Promise<firestore.DocumentSnapshot|null> {
this.verifySchemaIsCorrect(type, documentData);
const collectionName = this.getCollectionName(type);
return await this.addDocument(collectionName, documentData);
}
// FirebaseConnection.test.ts
import * as firebaseTesting from "#firebase/testing";
import {RecordTypes} from "../../../../shared";
import FirestoreConnection from "../FirestoreConnection";
/* * * * * * * * * * * * * * * * * * * * *
Setup
* * * * * * * * * * * * * * * * * * * * */
const createTestDatabase = (credentials): any => {
return firebaseTesting
.initializeTestApp({
projectId: 'testProject',
auth: credentials
})
.firestore();
};
const nullAllApps = firebaseTesting
.apps().map(app => app.delete());
const db = new FirestoreConnection('testShopDomain', createTestDatabase(null));
/* * * * * * * * * * * * * * * * * * * * *
Tests
* * * * * * * * * * * * * * * * * * * * */
test("creates new record", async () => {
const addedDocument = await db
.createNew(RecordTypes.globalRule, {
storeId : "dummyStoreId"
, globalPercent : 40
});
expect(addedDocument).toEqual({
storeId : "dummyStoreId"
, globalPercent : 40
, badProp : 0
});
}, 100000);
Is anyone able to tell why this is happening? Looking at the documentation this appears to be a lower level library: https://grpc.github.io/grpc/node/
Update
After it was suggested that the server/emulator was not found by gRPC, I ran firebase serve --only functions,firestore. Terminal showed emulators running on different ports for both services. Rerunning jest --watch now produces a slightly different error:
2 UNKNOWN:
at Object.<anonymous>.exports.createStatusError (node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener.Object.<anonymous>.InterceptingListener._callNext (node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.Object.<anonymous>.InterceptingListener.onReceiveStatus (node_modules/grpc/src/client_interceptors.js:618:8)
at callback (node_modules/grpc/src/client_interceptors.js:847:24)
That gRPC error means that no server is running at the address you are trying to connect to, or a connection to that server cannot be established for some reason. If you are trying to connect to a local Firestore emulator, you should verify that it is running and that you can connect to it outside of a test.
Firebase functions was hiding the underlying error. This was solved in 2 steps:
enabling logging in the the admin SDK with firestore.setLogFunction()
projectId testProject was invalid. Changing the projectId to testproject with all lowercase letters cleared this error.
unset your proxy
unset https_proxy;unset http_proxy

How to call a function inside webdriverio test configuration file

The url shows a WebdriverIO test runner configuration
https://webdriver.io/docs/configurationfile.html
It has got many hooks. Consider the hook onComplete I want to write a function, may be a function to create a file. In another file and call that function inside the onComplete hook. Could you please help me to achieve this.
Yes, you pretty much described the flow.
Define your function in a file and export it:
module.exports = (() => {
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* > Def: Polls the DOM until the given 'desiredState' is found.
* #param {string} desiredState ['loading', 'interactive', 'complete']
* #returns {Promise} WebdriverIO Promise
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
browser.addCommand('waitForReadyState', (desiredState) => {
let foundState;
browser.waitUntil(() => {
foundState = browser.execute('return document.readyState;');
console.log(`\n> Waiting for page to load ... | Current state: '${foundState}'`);
return foundState === desiredState;
}, browser.options.waitforTimeout, `Timeout before expected state! Found: '${foundState}' | Expected: '${desiredState}'`);
});
})();
Then, import it in the desired hook (e.g: for a custom_command, the before hook):
before: function (capabilities, specs) {
require('./test/custom_commands/waitForReadyState');
}
You can easily reproduce the model to implement logging & file manipulation functions that you need to run in the onComplete hook.
its maybe late but here is how you can do it :
/** file to keep your function should be in es5 or you have to add babel to covert it to es6 before WebdriverIO start **/
test.js
module.exports = function foo(){
console.log('here');
}
in config file //before export.config:
const foo = require('path-to-test.js');
use foo() in onComplete() hook

NodeJS Dynamic Service Loader & Runner

Context:
I'm trying to build a few slack hooks / notification services for a channel I'm active on, being the cheap-skate finance savvy person that I am, I'd like to make use of a free service as such (trail Heroku accounts, or similar products), thus I'd like to be able to run multiple services on a single instance.
I've created a generic runner, that should be based on a config and be able to pick up some node modules and supply them the config settings.
I'm using the following node_modules:
"auto-loader": "^0.2.0",
"node-cron": "^1.2.0",
"read-yaml": "^1.1.0"
config.yml
foo:
cron: 1 * * * *
url: http://www.foo.com
team:
-
slackId: bar
bnetId: 1
eloId: 1
-
slackId: baz
bnetId: 2
eloId: 2
app.js
const autoLoader = require('auto-loader');
const readYaml = require('read-yaml');
const cron = require('node-cron');
const services = autoLoader.load(__dirname +'/services')
readYaml('config.yml', function(err, conf) {
if (err) throw err;
Object.keys(conf).forEach(function (key) {
console.log('Creating CRON for ' + key);
if(cron.validate(conf[key].cron)) {
console.log(conf[key].cron, '-> is valid cron');
// the cron task below does not seem to fire ever
cron.schedule(conf[key].cron, function(){
services[key](conf[key]);
});
} else {
console.log('Cron invalid for::' + key)
}
});
});
service/foo.js
module.exports = function (config) {
console.log('foo entered!!');
console.log(config)
}
Question:
What am I missing? If I remove the cron schedule, my services get hit, thus my assumptions are as follows...
Either I'm missing something conceptually about how long running process are meant to work in NodeJS (as this is my first), or I'm missing a super (not obvious) to me bug.
How do you create a long running task/process in NodeJS with separate scheduled code sections / tasks?
The code itself works as expected. The issue appears to be with the configuration of the cron.
cron: 1 * * * * will run at 1 minute past the hour.
cron: "*/1 * * * *" # would run it every minute
cron: "*/5 * * * *" # would run it every 5 minutes
cron: "*/10 * * * * *" # would run every 10 seconds

Resources