With a JS script, I retrieve the stream arn from my DynamoDB table.
I will like to send this arn to serverless.yml file to use it in my function.
My serverless version:
$ serverless -v
Framework Core: 2.71.0 (standalone)
Plugin: 5.5.3
SDK: 4.3.0
Components: 3.18.1
My JS script works:
"use strict";
const AWS = require("aws-sdk");
async function run() {
const region = 'eu-west-3';
const tableName = 'dev-Connect-TrzConnect';
const dynamoDBStreams = await getDynamoDBStreams(region, tableName);
let streamArn = null;
dynamoDBStreams.Streams.forEach((stream) => {
streamArn = stream.StreamArn;
})
return streamArn;
}
const getDynamoDBStreams = async (region, tableName) => {
const dynamoStreams = new AWS.DynamoDBStreams({
region: region,
});
const params = {
TableName: tableName,
};
return dynamoStreams.listStreams(params).promise();
};
run().then((r) => console.log(r))
Now, I have no idea how to retrieve the value of streamArn variable in serverless.yml and, use it there:
functions:
createStatementFiles:
handler: lambda/statement.php
timeout: 899 # 14min 59s
layers:
- arn:aws:lambda:#{AWS::Region}:<account_id>:layer:php-73:1
role: CreateStatementFilesRole
reservedConcurrency: 10
events:
- stream:
type: dynamodb
arn: ${streamArn}
filterPatterns:
- eventName: [INSERT]
dynamodb:
NewImage:
__partitionKey:
S: [statementBalance]
I search to have something like this:
- stream:
type: dynamodb
arn: ${streamArn}
I read this documentation https://www.serverless.com/framework/docs/guides/plugins/creating-plugins but I did not understand at all how to solve my need.
Can you please help me ?
Related
I have managed to use fleek to update IPFS via straight javascript. I am now trying to add this functionality to a clean install of a svelteKit app. I think I am having trouble with the syntax around imports, but am not sure what I am doing wrong. When I click the button on the index.svelte I get the following error
Uncaught ReferenceError: require is not defined
uploadIPFS upload.js:3
listen index.mjs:412..........(I truncated the error here)
A few thoughts
I am wondering if it could be working in javascript because it is being called in node (running on the server) but running on the client in svelte?
More Details
The index.svelte file looks like this
<script>
import {uploadIPFS} from '../IPFS/upload'
</script>
<button on:click={uploadIPFS}>
upload to ipfs
</button>
the upload.js file looks like this
export const uploadIPFS = () => {
const fleek = require('#fleekhq/fleek-storage-js');
const apiKey = 'cZsQh9XV5+6Nd1+Bou4OuA==';
const apiSecret = '';
const data = 'pauls test load';
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch (e) {
console.log('error', e);
}
};
testFunctionUpload(data);
};
I have also tried using the other import syntax and when I do I get the following error
500
global is not defined....
import with the other syntax is
import fleekStorage from '#fleekhq/fleek-storage-js';
function uploadIPFS() {
console.log('fleekStorage',fleekStorage)
};
export default uploadIPFS;
*I erased the api secret in the code above. In future I will store these in a .env file.
Even more details (if you need them)
The file below will update IPFS and runs via the command
npm run upload
That file is below. For my version that I used in svelte I simplified the file by removing all the file management and just loading a variable instead of a file (as in the example below)
const fs = require('fs');
const path = require('path');
const fleek = require('#fleekhq/fleek-storage-js');
require('dotenv').config()
const apiKey = process.env.FLEEK_API_KEY;
const apiSecret = process.env.FLEEK_API_SECRET;
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data,
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch(e) {
console.log('error', e);
}
}
// File management not used a my svelte version to keep it simple
const filePath = path.join(__dirname, 'README.md');
fs.readFile(filePath, (err, data) => {
if(!err) {
testFunctionUpload(data);
}
})
I'm trying to listen to events emitted from the USDT contract Transfer function using ethers.js (not web3) in a node.js application.
When I run the script, the code runs with no errors and then quickly exits. I'd expect to get the event logs. I'm not sure what step I'm missing.
I've tested this script by calling the getOwner() method and console logging that result, this works fine, so my connection to mainnet is ok.
I'm using alchemy websocket.
My index.js file
const hre = require("hardhat");
const ethers = require('ethers');
const USDT_ABI = require('../abis/USDT_ABI.json')
async function main() {
const usdt = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
const provider = new ethers.providers.WebSocketProvider("wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API");
const contract = new ethers.Contract(usdt, USDT_ABI, provider)
contract.on('Transfer', (from, to, value) => console.log(from, to, value))
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
My hardhat.config.js file
require("#nomiclabs/hardhat-waffle");
require('dotenv').config()
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
const accounts = await ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
paths: {
artifacts: './src/artifacts',
},
networks: {
mainnet: {
url: "wss://eth-mainnet.ws.alchemyapi.io/v2/MY_API",
accounts: [`0x${process.env.PRIVATE_KEY}`]
},
hardhat: {
chainId: 1337
},
},
solidity: "0.4.8"
};`
I solved this by removing
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
and just calling main. It's recommended in the hardhat docs to use the .then and .catch code but when running a long running process like this script does with contract.on(), it causes the script to exit.
I do this:
const ethers = require('ethers');
const abi = [{...}]
const contractAddress = '0x000...'
const webSocketProvider = new ethers.providers.WebSocketProvider(process.env.ETHEREUM_NODE_URL, process.env.NETWORK_NAME);
const contract = new ethers.Contract(contractAddress, abi, webSocketProvider);
contract.on("Transfer", (from, to, value, event) => {
console.log({
from: from,
to: to,
value: value.toString(),
data: event
});
});
The event return all data related to event and transaction.
I'm following this tutorial where we're creaing an app using next.js. We're using sqlite, and testing a database. In the tutorial we write the following 'database-test.js' file:
const sqlite = require('sqlite');
async function setup() {
const db = await sqlite.open('./mydb.sqlite');
await db.migrate({force: 'last'});
const people = await db.all('SELECT * FROM person');
console.log('ALL PEOPLE', JSON.stringify(people, null, 2));
const vehicles = await db.all('SELECT * FROM vehicle');
console.log('ALL VEHICLES', JSON.stringify(vehicles, null, 2));
}
setup();
I get the following error when I $node database-test.js:
(node:26446) UnhandledPromiseRejectionWarning: Error: sqlite: filename cannot be null / undefined
I don't really understand why we are opening a .sqlite file, and not a .db file. I've made sure I have the correct path to the .sqlite file. What is the cause of this error and how might I fix it? I can't seem to find any other documentation or examples of the .open function.
As #ANimator120 was mentioned but with some tweaks.
Use require because it runs on server side.
Install sqlite3 by npm i sqlite3.
Then add path to your migrations folder if it's not in the project root.
const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');
async function openDb() {
return sqlite.open({
filename: './database.db',
driver: sqlite3.Database,
});
}
async function setup() {
const db = await openDb();
await db.migrate(
{
migrationsPath: './src/migrations', //add cutom path to your migrations
force: 'last'
}
);
const people = await db.all('SELECT * FROM Person');
console.log('all person', JSON.stringify(people, null, 2));
const vehicle = await db.all(`SELECT a.*, b.* FROM Person as a
LEFT JOIN Vehicle as b
ON a.id = b.ownerId
`);
console.log('all vehicles', JSON.stringify(vehicle, null, 2));
}
setup();
Everything working fine, at least for me.
You need to npm install both sqlite and sqlite3
The correct way to use the open() method would be.
const sqlite = require('sqlite');
const sqlite3 = require('sqlite3')
const {open} = require('sqlite')
async function openDB (){
return open({
filename : './mydb.sqlite',
driver: sqlite3.Database
})
}
async function setup(){
const db = await openDB();
await db.migrate({force : 'last'});
}
setup();
Turns out they were using sqlite 3.0.3 in the tutorial. With sqlite3, the correct way to use open() in this case is:
import { open } from 'sqlite'
import sqlite3 from 'sqlite3'
// you would have to import / invoke this in another file
export async function openDB () {
return open({
filename: './mydb.sqlite',
driver: sqlite3.Database
})
}
I am following the how to graphql tutorial where I am setting up a simple graphql server.
index.js
const { GraphQLServer } = require('graphql-yoga');
// 1
let links = [{
id: 'link-0',
url: 'www.howtographql.com',
description: 'Fullstack tutorial for GraphQL'
}];
const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
// 2
feed: () => links,
},
// 3
Link: {
id: (parent) => parent.id,
description: (parent) => parent.description,
url: (parent) => parent.url,
}
};
// 3
const server = new GraphQLServer({
typeDefs:'./schema.graphql',
resolvers,
});
server.start(() => console.log(`Server is running on http://localhost:4000`));
As you can see, I am referencing my schema file when creating the GraphQLServer. When I run the server, however, I am getting the following error:
/Users/BorisGrunwald/Desktop/programmering/Javascript/GraphQL/hackernews-node/node_modules/graphql-yoga/dist/index.js:418
throw new Error("No schema found for path: " + schemaPath);
^
My file structure:
Can anyone spot the error?
You gave the path ./schema.graphql which makes node look for the file in the directory where you run it instead of the correct location which is 'src/schema.graphql'.
So you need to change the path to:
//...
typeDefs: 'src/schema.graphql',
//...
So we have a project, in which Crashlytics and analytics are set-up and currently functioning. However I am not able to successfully implement the cloud functions for the three triggers found here : Crashlytics Events.
While testing using other cloud functions such as when there are read/write operations on the database, the functions execute correctly. When deploying the functions folder to firebase, I get no errors in regards to the triggers and the code is very similar to the samples on Github. I have made sure that the SDK is up to date and that I have run npm install in the functions folder for any dependencies.
Here is the JS file:
'use strict';
const functions = require('firebase-functions');
const rp = require('request-promise');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Helper function that posts to Slack about the new issue
const notifySlack = (slackMessage) => {
// See https://api.slack.com/docs/message-formatting on how
// to customize the message payload
return rp({
method: 'POST',
uri: functions.config().slack.webhook_url,
body: {
text: slackMessage,
},
json: true,
});
};
exports.postOnNewIssue = functions.crashlytics.issue().onNewDetected((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const slackMessage = `<!here|here> There is a new issue - ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted new issue ${issueId} successfully to Slack`);
});
});
exports.postOnRegressedIssue = functions.crashlytics.issue().onRegressed((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const resolvedTime = data.resolvedTime;
const slackMessage = `<!here|here> There is a regressed issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform}. This issue was previously ` +
`resolved at ${new Date(resolvedTime).toString()}`;
return notifySlack(slackMessage).then(() => {
return console.log(`Posted regressed issue ${issueId} successfully to Slack`);
});
});
exports.postOnVelocityAlert = functions.crashlytics.issue().onVelocityAlert((event) => {
const data = event.data;
const issueId = data.issueId;
const issueTitle = data.issueTitle;
const appName = data.appInfo.appName;
const appPlatform = data.appInfo.appPlatform;
const latestAppVersion = data.appInfo.latestAppVersion;
const crashPercentage = data.velocityAlert.crashPercentage;
const slackMessage = `<!here|here> There is an issue ${issueTitle} (${issueId}) ` +
`in ${appName}, version ${latestAppVersion} on ${appPlatform} that is causing ` +
`${parseFloat(crashPercentage).toFixed(2)}% of all sessions to crash.`;
return notifySlack(slackMessage)/then(() => {
console.log(`Posted velocity alert ${issueId} successfully to Slack`);
});
});
When I tried to deploy Crashlytics events, I was greeted with the following error message.
⚠ functions: failed to update function crashlyticsOnRegressed
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnNew
HTTP Error: 400, The request has errors
⚠ functions: failed to update function crashlyticsOnVelocityAlert
HTTP Error: 400, The request has errors
Sure enough, Cloud Function documentation no longer lists Crashlytics, which used to be under the section Crashlytics triggers. Perhaps Google no longer supports it.
According to this issue, the crashlytics function triggers were deprecated and removed in release 3.13.3 of the firebase-functions SDK.