"const config = new Config()" not defined - node.js

I'm quite new to NodeJS and I try to follow an example setting up a payment solution provided by Adyen. In their example code they give me this:
const config = new Config();
config.apiKey = MY_API_KEY;
config.merchantAccount = MY_ACCOUNT;
const client = new Client({ config });
client.setEnvironment("TEST");
const checkout = new CheckoutAPI(client);
const paymentsResponse = checkout.paymentMethods({
amount: {
currency: "EUR",
value: 1000,
},
countryCode: "NL",
channel: "Web",
merchantAccount: config.merchantAccount
}).then(res => res);
However (maybe not so surprising) I get the following error:
const config = new Config();
^
ReferenceError: Config is not defined
What should Config() be here? Should I define a new class? (class Config {}?) Or am I missing something? Like something to include? Same for client, how can I call .setEnvironment if Client is a class I create?
Any help appreciated.

Turned out you are supposed to import #adyen/api-library with:
npm install --save #adyen/api-library
Source

After installing the API library, you can include the modules:
const {Client, Config, CheckoutAPI} = require('#adyen/api-library');
Just place it at the top of the file where the rest of your code lives (i.e., where you make that checkout.paymentMethods() call), and you should be good to go!

Related

Unhandled Runtime Error Error: Configuration must contain `projectId`

I'm getting this error again and again. I've provided projectID as well via env file, still getting
I'm new to NextJS and sanity as well, please help me out, your help will be appreciated.
import sanityClient from '#sanity/client';
import imageUrlBuilder from '#sanity/image-url';
export const client = sanityClient({
projectId: process.env.NEXT_APP_PROJECT_ID,
dataset: 'production',
apiVersion: '2022-03-10',
useCdn: true,
token: process.env.NEXT_APP_SANITY_TOKEN
});
const builder = imageUrlBuilder(client);
export const urlFor = (source) => builder.image(source);
I'm following a tutorial on NextJS tutorial on youtube. I was expecting it to be run smoothly, but didn't work
So I have the same issue with you. So make sure your enviroment variables starts with VITE in case you are using VITE
In my case , I did with this way
import SanityClient from "#sanity/client"
import imageUrlBuilder from "#sanity/image-url";
// take these from sanity manage
export const client = new SanityClient({
projectId:import.meta.env.VITE_REACT_APP_SANITY_PROJECT_ID,
dataset:'production',
apiVersion:'2023-01-10',
useCdn:true,
token:import.meta.env.VITE_REACT_APP_SANITY_TOKEN,
})
const builder = imageUrlBuilder(client);
export const urlFor = (source : any) => builder.image(source);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
And my .env file is like this
VITE_REACT_APP_SANITY_PROJECT_ID = aweqfrstbsrgvsrtbvr
VITE_REACT_APP_SANITY_TOKEN = skm29cF1q1VsOgKIFty8D53j2dJKly9Fa..........
Make sure give a space in env file before and after the = sign

Invariant Violation: fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment

I'm trying to run a NodeJS app with an AWS Lambda handler. My package.json is very simple:
...
"dependencies": {
"aws-appsync": "^4.1.7",
"aws-sdk": "^2.1202.0",
"graphql-tag": "^2.12.6"
}
When I try to run anything I get:
Invariant Violation:
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.
For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
at new InvariantError (/Users/jamesdaniels/Code/node_modules/ts-invariant/lib/invariant.js:16:28)
at Object.exports.checkFetcher (/Users/jamesdaniels/Code/node_modules/apollo-link-http-common/lib/index.js:65:15)
at Object.createHttpLink (/Users/jamesdaniels/Code/node_modules/apollo-link-http/lib/bundle.umd.js:47:30)
at Object.exports.createAppSyncLink (/Users/jamesdaniels/Code/node_modules/aws-appsync/lib/client.js:144:201)
at new AWSAppSyncClient (/Users/jamesdaniels/Code/node_modules/aws-appsync/lib/client.js:214:72)
at Object.<anonymous> (/Users/jamesdaniels/Code/utils/appsync.js:16:23)
The error appears to be with the aws-appsync package. The error only occurs when I introduce that to my app:
const AWS = require("aws-sdk") // Works fine
const AUTH_TYPE = require("aws-appsync").AUTH_TYPE;
const AWSAppSyncClient = require("aws-appsync").default;
// GraphQL client config
const appSyncClientConfig = {
url: "https://xxxxxxxxxxxxxxxxx.appsync-api.eu-west-2.amazonaws.com/graphql",
region: "eu-west-2",
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: AWS.config.credentials,
},
disableOffline: true,
};
// Initialise the AppSync client
const appSyncClient = new AWSAppSyncClient(appSyncClientConfig);
An error is thrown from dependent modules aws-appsync > apollo-link-http > apollo-link-http-common.
Turns out the error message was telling me exactly what I needed to know. aws-appsync isn't designed for a back-end environment. It's intended for front-end environments, where fetch is available globally. In the back-end we need to create our own global variable for our own fetch if we want it to be available for any node packages that we've installed.
The solution is to download node-fetch and then follow the instructions in the "Provide Global Access" section:
Providing global access
To use fetch() without importing it, you can patch the global object in node:
// fetch-polyfill.js
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch'
if (!globalThis.fetch) {
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
}
// index.js
import './fetch-polyfill'
// ...

Shopify API Node/Express Cannot read properties of undefined (reading 'Rest')

Just starting off with Shopify, and trying to get an order. Following the Shopify API documentation, here is my code:
const Shopify = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
module.exports.getShopifyOrderById = async (orderId) => {
return await client.get({
path: `orders/${orderId}`,
});
}
I get the following error when I execute this code:
TypeError: Cannot read properties of undefined (reading 'Rest')
Can't seem to figure out what the issue is.
You need to use Object destructing to get the Shopify object or use default export like below.
const { Shopify } = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const Shopify = require('#shopify/shopify-api').default;
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const ShopifyLib = require('#shopify/shopify-api');
const client = new ShopifyLib.Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
This has to do with how ES6 modules are emulated in CommonJS and how you import the module. You can read about that here.

error passing empty credentials to firestore emulator

I am trying to seed some sample data into my local firestore emulator database. I adapted the example from this github issue
My code looks like this:
const {Firestore} = require('#google-cloud/firestore');
const {credentials} = require('grpc');
const db = new Firestore({
projectId: 'my-project-id',
servicePath: 'localhost',
port: 8100,
sslCreds: credentials.createInsecure(),
customHeaders: {
"Authorization": "Bearer owner"
}
});
async function load_data() {
await db.collection("mycollection").doc("myid").set({ foo: "test" })
}
load_data();
But I receive the error
this.credentials._getCallCredentials is not a function
Tested on node 10 and 12 with same error.
Library versions:
#google-cloud/firestore 3.5.1
grpc 1.24.2
Is there a better approach to writing to local emulated firestore? Or is there something wrong with my code?
The problem here is that you're trying to use two different implementations of gRPC together. Internally firestore uses #grpc/grpc-js, so that is what you should be using. You should only need to change the second line to const {credentials} = require('#grpc/grpc-js'); and switch the dependency to that library.

how to mock twilio in unit tests with either sinon/proxyquire or dependency inejction in node.js

Say I want to test a a user login controller that sends login codes via SMS with Twilio. How should I set up the test so that I can mock Twilio and see what codes it's sending back. My approach was to proxyquire the twilio client object and spy on it with sinon, but I don't think I'm getting it quite right.
controller user.js
var smsClient = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
module.exports = {
checkCode: function(phone){
var code = getNewCode();
smsClient.sms.messages.create({
from: config.get('twilio_phone_number'),
to: phone,
body: 'Your code :' + code
}, callback);
}
}
test file
var twilioMock = //what goes here??
var smsSpy = sinon.spy(twilioMock.sms.messages, 'create');
var User = proxyquire('../models/user', { 'mongoose': mongooseMock, 'smsClient': twilioMock });
... some describe and it statements ...
twilioMock.sms.messages.should.have.been.calledOnce() //this is where I don't know what I should be checking
// or is this the right way?
//smsSpy.should.have.been.calledOnce()
I am answering this very late but this might help someone.
I haven't used proxywire but it seems very similar to rewire (just by looking at your code). You should try the following:
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
I am more used to rewire. npm i rewire --save-dev. Using rewire you may try the following: (concept remains the same)
In your test:
var rewire = require('rewire');
var twilioMock = new twilio.RestClient(config.get('twilio_account_sid'), config.get('twilio_auth_token'));
var userController = rewire('./path_to_user.js') // notice use of rewire
beforeEach(function(){
this.smsClient = twilioMock; // `this` is available within your tests
userController.__set__('smsClient', this.smsClient);
});
it('should something', sinon.test(function(){
var smsSpy = this.spy(this.smsClient.sms.messages, 'create');
}));

Resources