Node: v8.6.0
Nodemailer: v4.6.4
This is my code:
const transport = nodemailer.createTransport({
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});
const generateHTML = (filename, options = {}) => {
const html = pug.renderFile(`${__dirname}/../views/email/${filename}.pug`,
options);
const inlined = juice(html);
return inlined;
}
exports.send = async (options) => {
const html = generateHTML(options.filename, options);
const text = htmlToText.fromString(html);
const mailOptions = {
from: `Site <noreply#domain.com>`,
to: options.user.email,
subject: options.subject,
html,
text
};
const sendMail = P.promisify(transport.sendMail, transport);
return sendMail(mailOptions);
}
When i execute sendMail i get this fail:
TypeError: Cannot read property 'getSocket' of undefined↵ at sendMail (/Users/...../node_modules/nodemailer/lib/mailer/index.js:143:24
I check the mention line and is this one:
if (typeof this.getSocket === 'function') {
this.transporter.getSocket = this.getSocket;
this.getSocket = false;
}
In my case, I received this error when I was trying to promisify the transport. Omit the callback parameter and it will natively return a promise. No need to promisify.
Try this.
const transport = nodemailer.createTransport({
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});
const generateHTML = (filename, options = {}) => {
const html = pug.renderFile(`${__dirname}/../views/email/${filename}.pug`,
options);
const inlined = juice(html);
return inlined;
}
exports.send = async (options) => {
const html = generateHTML(options.filename, options);
const text = htmlToText.fromString(html);
const mailOptions = {
from: `Site <noreply#domain.com>`,
to: options.user.email,
subject: options.subject,
html,
text
};
return transport.sendMail(mailOptions)
.then((stuff) => { console.log(stuff); })
.catch((err) => { console.log(err); }) ;
}
Related
I have a challenge with express-fileupload when a user doesn't upload a file that is meant to be optional.
Someone should please help me out.
This is my code:
const file = req.files.document;
const file2 = req.files.document2;
const uploader = req.body.fullname;
const filename = `CV_${uploader}_${file.name}`;
const filename2 = `Cover_${uploader}_${file2.name}`;
let savedFile = filename.replace(/\s+/g, "");
let savedFile2 = filename2.replace(/\s+/g, "");
const path = "uploads/" + savedFile;
const path2 = "uploads/" + savedFile2;
file.mv(path, (err) => {
if (err) {
console.log(err);
}
});
file2.mv(path2, (err) => {
if (err) {
console.log(err);
}
});
The second file is optional for the user to upload. When the user doesn't upload it, it shows an error.
Please, how can I make it optional from here.
It shows an error like this:
Type Error: Cannot read property 'name' of undefined
Thank you so much.
So, I was able to find my way around the whole thing.
I did it like this...
app.post("/form", (req, res) => {
const file = req.files.document;
const file2 = req.files.document2;
const uploader = req.body.fullname;
const filename = `CV_${uploader}_${file.name}`;
let savedFile = filename.replace(/\s+/g, "");
const path = "uploads/" + savedFile;
file.mv(path, (err) => {
if (err) {
console.log(err);
}
});
// function to save file2 to server if it exists and send the filename to be used outside the function
const filename2 = file2 ? `Cover_${uploader}_${file2.name}` : null;
let savedFile2 = filename2 ? filename2.replace(/\s+/g, "") : null;
const path2 = filename2 ? "uploads/" + savedFile2 : null;
if (file2 && file2.name) {
const filename2 = `Cover_${uploader}_${file2.name}`;
let savedFile2 = filename2.replace(/\s+/g, "");
const path2 = "uploads/" + savedFile2;
file2.mv(path2, (err) => {
if (err) {
console.log(err);
}
});
}
// Saving to the database...
const date = new Date();
const dateNow = moment(date).format("llll");
const job = new Jobs({
position: req.body.positions,
language: req.body.lang,
fullName: req.body.fullname,
gender: req.body.gender,
education: req.body.education,
email: req.body.email,
address: req.body.address,
phone: req.body.phone,
fileCV: savedFile,
fileCover: savedFile2,
date: dateNow,
});
job.save((err) => {
if (!err) {
res.render("success");
}
});
// Sending to mail server
const output = `
<p> You have a new applicant! </p>
<h2> Contact Details </h2>
<ul>
<li>position: ${req.body.positions}</li>
<li>language: ${req.body.lang} </li>
<li>fullName: ${req.body.fullname}</li>
<li>gender: ${req.body.gender}</li>
<li>email: ${req.body.email}</li>
<li>address: ${req.body.address}</li>
<li>phone: ${req.body.phone}</li>
<li>education: ${req.body.education}</li>
</ul>
`;
const transporter = nodemailer.createTransport({
service: "localhost",
port: 1025,
secure: false, // true for 465, false for other ports
auth: {
user: "project.1", // generated ethereal user
pass: "secret.1", // generated ethereal password
},
tls: {
rejectUnauthorized: false,
},
});
let senderName = req.body.fullname;
let senderEmail = req.body.email;
//send mail with unicode symbols
let mailOptions = {
from: `"${senderName}" <${senderEmail}>`, // sender address
to: "mikejuwon737#gmail.com, sjobopisa#gmail.com", // list of receivers
subject: "Job Application ✔", // Subject line
text: "Check out my details here...", // plain text body
html: output, // html body
attachments: [
{ filename: `${savedFile}`, path: `${path}` },
{ filename: `${savedFile2}`, path: `${path2}` },
], // list of attachments
};
// sending mail with defined transport object
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
} else {
console.log("Message sent: %s", info.messageId);
// console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
});
});
I need help sending a specific number of emails with nodemailer, lets say i want to send 20 emails to a specific person.
This is my code.
const transporter = nodemailer.createTransport(smtpTransport({
host: "smpt.gmail.com", //smtp server
port: 587,
pool: true,
secure: false, // true for 465, false for other ports
auth: {
user: "testtest#gmail.com", // mail
pass: "testtesttest" // password
}
}));
transporter.close();
// setup email data with unicode symbols
let mailOptions = {
from: '"Test Test" <testtest#gmail.com>', // sender address
to: mailto, // list of receivers
subject: args[1], // Subject line
text: args[2] //
};
async function sendMail() {
let info = await transporter.sendMail(mailOptions);
sending = true;
}
const SendingMessage = setInterval(() => {
var mailto = args[0];
mailOptions.subject = args[1];
var mailtxt = args[2];
sendMail();
}, 1500);
How do i make it send a message like "hey" to test#test.com 5 times only. because currently it just sends "hey" until i hit my smtp sending limit
First create an array of mail content you want to send, for example;
const mails2send = [
{
from: '..',
to: '..',
subject: '..'
text: '..'
},
{
from: '..',
to: '..',
subject: '..'
text: '..'
},
{
from: '..',
to: '..',
subject: '..'
text: '..'
}
]
Modify the sendMail function to take in argument.
async function sendMail(mailOptions) {
let info = await transporter.sendMail(mailOptions);
sending = true;
return sending;
}
then map through the mails2send
mails2send.forEach( item => sendMail(item ))
Update It appears you may be talking about your setInterval function
let counter = 0;
const SendingMessage = setInterval(() => {
var mailto = args[0];
mailOptions.subject = args[1];
var mailtxt = args[2];
sendMail();
if (counter === 4) {
return clearInterval(SendingMessage); //<-- clear the interval when reach 5.
}
counter++ //<-- counter increment.
}, 1500);
Umm, maybe this is what you want ?
This will send mail to each of address 5 times and blocking / synchronously.
const nodemailer = require("nodemailer");
function template(address) {
return {
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: address, // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
};
}
async function main() {
const transport = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "augustine.kozey54#ethereal.email",
pass: "5Jq3GYxyTu51Pxx8Hr",
},
});
const addresses = [
"budi#mail.com",
"ami#mail.com",
"indah#mail.com",
"july#mail.com",
"meita#mail.com",
];
/*
Using for loop
*/
// const mailer = [];
// for (let i = 0; i < addresses.length; i++) {
// for (let j = 0; j < 5; j++) {
// mailer.push(transport.sendMail(template(addresses[i])));
// }
// }
/*
Using for map
*/
const mailer = addresses
.map((address) => {
return [...Array(5)].map((i) => transport.sendMail(template(address)));
})
.flatMap((array) => [...array]);
return await Promise.all(mailer);
}
main()
.then((res) => console.log(res))
.catch((e) => console.error(e));
const nodemailer = require("nodemailer");
function template(address) {
return {
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: address, // list of receivers
subject: "Hi", // Subject line
text: "Hi", // plain text body
// html: "<b>Hello world?</b>", // html body
};
}
async function main() {
const transport = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "augustine.kozey54#ethereal.email",
pass: "5Jq3GYxyTu51Pxx8Hr",
},
});
const addresses = [
"test#gmail.com"
];
/*
Using for loop
*/
// const mailer = [];
// for (let i = 0; i < addresses.length; i++) {
// for (let j = 0; j < 5; j++) {
// mailer.push(transport.sendMail(template(addresses[i])));
// }
// }
/*
Using for map
*/
const mailer = addresses
.map((address) => {
return [...Array(5)].map((i) => transport.sendMail(template(address)));
})
.flatMap((array) => [...array]);
return await Promise.all(mailer);
}
main()
.then((res) => console.log(res))
.catch((e) => console.error(e));
I have this ngrx effect in my angular app that send an http request using httpClient
#Injectable()
export class MyEffects {
constructor(private actions$: Actions, private httpClient: HttpClient) {
}
sendEmail$: Observable<Action> = createEffect(() => this.actions$.pipe(
ofType(sendEmail),
concatMap(action =>
this.httpClient.post('https://us-central1-<PROJECT_ID>.cloudfunctions.net/myApi', action.data).pipe(
map(() => actionFinished({status: HttpActionsStatus.SUCCESS})),
catchError(() => of(actionFinished({status: HttpActionsStatus.ERROR})))
)
)
));
}
When I run this with firebase emulator (http://localhost:5001/<PROJECT_ID>/us-central1/myApi it works just fine, but when I deploy the app and trigger the request I get this error
Access to XMLHttpRequest at 'https://us-central1-<PROJECT_ID>.cloudfunctions.net/myApi' from origin 'https://<PROJECT_ID>.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my functions file
const fs = require('fs');
const {promisify} = require('util');
const readFile = promisify(fs.readFile);
const admin = require('firebase-admin');
const handlebars = require('handlebars');
const nodemailer = require('nodemailer');
const functions = require('firebase-functions');
const email = decodeURIComponent(functions.config().gmail.email);
const password = encodeURIComponent(functions.config().gmail.password);
const cors = require('cors')({origin: true, optionsSuccessStatus: 200});
admin.initializeApp();
const transporter = nodemailer.createTransport({
service: 'gmail',
secure: false,
port: 25,
auth: {
user: email,
pass: password
},
tls: {
rejectUnauthorized: false
}
});
exports.myApi = functions.https.onRequest((request: any, response: any) =>
cors(request, response, () =>
readHTMLFile('../src/assets/html/new_message.html', (err: any, html: string) => {
const template = handlebars.compile(html);
const htmlToSend = template(request.body);
const mailOptions = {
to: email,
from: request.body.senderEmail,
subject: request.body.subject,
html: htmlToSend
};
return transporter.sendMail(mailOptions, async (error: any, {}) => {
if (!error) {
const responseEmailOptions = {
to: request.body.senderEmail,
from: email,
subject: request.body.subject,
html: await readFile('../src/assets/html/auto_reply.html'),
};
transporter.sendMail(responseEmailOptions);
return response.status(200).send(request.body);
}
throw error;
});
})
)
);
const readHTMLFile = (path: string, callback: any) => {
fs.readFile(path, {encoding: 'utf-8'}, (err: any, html: string) => {
if (!err) {
return callback(null, html);
}
throw err;
});
};
Basically what it does it to send an email and a verification email back to the sender.
I'll Appreciate your help!
const Koa = require('koa');
const cors = require('#koa/cors');
var https = require('https');
var http = require('http');
const { default: enforceHttps } = require('koa-sslify');
const next = require('next');
const { default: createShopifyAuth } = require('#shopify/koa-shopify-auth');
const dotenv = require('dotenv');
const { verifyRequest } = require('#shopify/koa-shopify-auth');
const session = require('koa-session');
const { ApiVersion } = require('#shopify/koa-shopify-graphql-proxy');
const { default: graphQLProxy } = require('#shopify/koa-shopify-graphql-proxy');
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 9000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const Router = require('koa-router');
const processPayment = require('./server/router');
const helloMessage = require('./server/router');
const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY } = process.env;
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
var bodyParser = require('koa-bodyparser');
const apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXx";
const apiSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const scopes = 'read_products,write_script_tags,read_script_tags,read_customers, write_customers,read_product_listings,read_orders';
const forwardingAddress = "https://qualzz.com:9000";
//const forwardingAddress = "https://18.188.232.26:9000"
const appInstallAddress = "https://qualzz.com/api/user/webhooks/userInStalledApp";
const createUserUrlLink = "https://qualzz.com/api/user/createUser";
const forgotPasswordUrl = "https://qualzz.com/api/user/forgotPassword";
var fs = require('fs');
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
var email = "";
//var key = fs.readFileSync('/etc/nginx/qualzz.com.key');
//var cert = fs.readFileSync('/etc/nginx/qualzz_ssl.crt');
//var credentials = {key: key, cert: cert};
//var httpsServer = https.createServer(credentials, Koa);
// httpsServer.listen(port,()=>{
// console.log(`> Ready on http://localhost:${port}`);
//});
app.prepare().then(() => {
console.log("Started")
const server = new Koa();
const router = new Router();
server.use(enforceHttps({
port: port
}));
server.use(cors());
server.use(bodyParser());
server.use(session(server));
server.keys = ["XXXXXXXXXXXXXXXXXXXXX"];
router.get('/', processPayment);
router.get('/hello', async (ctx) => {
ctx.body = {
status: 'success',
message: 'hello, world!'
};
})
module.exports = router;
router.get('/shopify', (ctx,next) => {
console.log("ctx -->",ctx.query)
const shop = ctx.query.shop;
if (shop) {
const state = nonce();
const redirectUri = forwardingAddress + '/shopify/callback';
const installUrl = 'https://' + shop +
'/admin/oauth/authorize?client_id=' + apiKey +
'&scope=' + scopes +
'&state=' + state +
'&redirect_uri=' + redirectUri;
ctx.cookies.set('state', state);
console.log("install url ---->",installUrl)
ctx.redirect(installUrl);
} else {
return ctx.status(400).send('Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request');
}
});
router.get('/shopify/callback', (ctx,next) => {
console.log("in ctx call",ctx.query);
const { shop, hmac, code, state } = ctx.query;
const stateCookie = cookie.parse(ctx.headers.cookie).state;
if (state !== stateCookie) {
return ctx.status(403).send('Request origin cannot be verified');
}
if (shop && hmac && code) {
const map = Object.assign({}, ctx.query);
delete map['signature'];
delete map['hmac'];
const message = querystring.stringify(map);
const providedHmac = Buffer.from(hmac, 'utf-8');
const generatedHash = Buffer.from(
crypto
.createHmac('sha256', apiSecret)
.update(message)
.digest('hex'),
'utf-8'
);
let hashEquals = false;
try {
hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)
} catch (e) {
hashEquals = false;
};
if (!hashEquals) {
return res.status(400).send('HMAC validation failed');
}
const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
const accessTokenPayload = {
client_id: apiKey,
client_secret: apiSecret,
code,
};
// setTimeOut(()=>{
console.log("near to redirect"+email);
ctx.redirect('https://app.qualzz.com?email='+email);
// },500);
//ctx.redirect('http://www.google.com');
request.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
const createScriptTagUrl = 'https://'+shop+'/admin/script_tags.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
};
const scriptTagBody = {"script_tag":
{ "event": "onload",
"src": "https://app.qualzz.com/assets/trackingScript/webtracking.js"
}
};
var redirectUrl = 'https://app.qualzz.com?email='+email;
const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
// const saveCustomerUrl = 'http://ec2-18-216-255-14.us-east-2.compute.amazonaws.com:8080/user/webhooks/userInStalledApp';
const saveCustomerUrl = appInstallAddress;
request.get(shopRequestUrl, { headers: shopRequestHeaders })
.then((shopResponse) => {
//script tag try 3
const shopDetail = {
"shop":{
"id":JSON.parse(shopResponse).shop.id,
"email":JSON.parse(shopResponse).shop.email,
"phone":JSON.parse(shopResponse).shop.phone,
"name":JSON.parse(shopResponse).shop.name,
"domain":JSON.parse(shopResponse).shop.domain
}
}
console.log(shopDetail.shop.domain+">>>>>>>>>>>>>>>>>>emailemailxxx<<<<<<<<");
email = shopDetail.shop.email+'&url='+shopDetail.shop.domain;
console.log(email);
const createUser = {
"email":JSON.parse(shopResponse).shop.email,
"fullName":JSON.parse(shopResponse).shop.name,
"password":'XXXXXXXXX',
"shopify":true
}
const createUserUrl = createUserUrlLink;
request.post({
url:saveCustomerUrl,
body:shopDetail,
json:true
},function(error,response,body){
if(!error){
console.log("success in saving"+error+response+body);
request.post({
url: createScriptTagUrl,
body: scriptTagBody,
headers: shopRequestHeaders,
json: true
}, function( error,response,body){
if (ctx) {
console.log("before route -->",redirectUrl)
console.log("ctxroute --->",ctx)
ctx.redirect(redirectUrl);
} else {
ctx.body = {
status:error.statusCode,
message:'error'
}
}
});
ctx.redirect('https://app.qualzz.com?email='+email);
}
})
.catch((error) => {
res.status(error.statusCode);
});
request.post({
url:createUserUrl,
body:createUser,
json:true
},function(error,response,body){
if(!error){
console.log("success in user creation");
}else{
console.log('Error in user creation',error)
}
})
.catch((error)=>{
// redirectSite();
ctx.body ={
status:error.statusCode,
message:'error'
}
})
})
.catch((error) => {
ctx.body = {
status:error.statusCode,
message:'error'
}
});
function redirectSite(){
server.use((ctx,next) => {
});
//script tag try 2
}
})
.catch((error) => {
ctx.body = {
status:error.statusCode,
message:'error'
}
});
} else {
res.status(400).send('Required parameters missing');
}
});
//var dummyObj;
var shopifyObject;
router.post('/shopify/plan/upgrade',async(ctx)=>{
console.log("ctx --->",ctx.request.body);
obj = ctx.request.body.plan;
shopifyObject = ctx.request.body.userInfo;
localStorage.setItem('shopifyObject',JSON.stringify(shopifyObject));
console.log("shopify object is --->",shopifyObject)
const upgradeUrl= ctx.request.body.url;
// ctx.redirect('/');
// ctx.redirect(upgradeUrl);
ctx.body = {
status:"200",
message:'success'
}
});
// console.log("shopiufy object--->",shopifyObject)
obj = {
name: 'Recurring charge',
price: 20.01,
return_url: "https://qualzz.com:9000",
test: true
}
//console.log("calling this ... ");
server.use(
createShopifyAuth({
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
scopes: ['write_products', 'read_products'],
async afterAuth(ctx) {
const { shop, accessToken } = ctx.session;
console.log("Object is -->",obj);
// localStorage.setItem('shopifyObject', shopifyObject)
ctx.cookies.set('shopOrigin', shop, { httpOnly: false });
const stringifiedBillingParams = JSON.stringify({
recurring_application_charge: obj
})
console.log("in --->",obj)
const options = {
method: 'POST',
body: stringifiedBillingParams,
credentials: 'include',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
};
const confirmationURL = await fetch(
`https://${shop}/admin/api/2019-04/recurring_application_charges.json`, options)
.then((response) => response.json())
.then((jsonData) => jsonData.recurring_application_charge.confirmation_url)
.catch((error) => console.log('error', error));
console.log("Confirmation url",confirmationURL)
ctx.redirect('/');
ctx.redirect(confirmationURL);
},
}),
);
server.use(graphQLProxy({version: ApiVersion.April19}))
server.use(router.routes());
// server.use(cors());
server.use(verifyRequest({authRoute: '/shopify/auth', fallbackRoute: '/shopify/auth'}));
server.use(async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
return
});
var key = fs.readFileSync('/etc/nginx/qualzz.com.key');
var cert = fs.readFileSync('/etc/nginx/qualzz_ssl.crt');
var credentials = {key: key, cert: cert};
https.createServer(credentials, server.callback()).listen(port);
});
I have created Shopify app after installing app I want to take the user to my site with email and shop URL as param so as in above code I am redirecting user with email and URL but i am not able to get current user email and store url am getting previous user details so where can i write redirect code so that i will get proper result.
help me for this..
The correct use is as follows. Shopify merchant installs your App. Once they approve your App, the callback to your App comes with the shop name and a token allowing you access to the Shop details. Use an API call with that token to get the email address you need.
I am starting the ginit module but getting the error like this:
=> octokit.authenticate() is deprecated. Use "auth" constructor
option instead.
How can I fix it?
my code
module.exports = {
getInstance: () => {
return octokit;
},
setGithubCredentials : async () => {
const credentials = await inquirer.askGithubCredentials();
octokit.authenticate(
_.extend(
{
type: 'basic',
},
credentials
)
);
},
}
Maybe you code from this article: https://www.sitepoint.com/javascript-command-line-interface-cli-node-js/
And my solution is below
const Octokit = require("#octokit/rest");
const Configstore = require("configstore");
const pkg = require("../package.json");
const _ = require("lodash");
const CLI = require("clui");
const Spinner = CLI.Spinner;
const chalk = require("chalk");
const inquirer = require("./inquirer");
const conf = new Configstore(pkg.name);
module.exports = {
getInstance: () => {
return global.octokit;
},
getStoredGithubToken: () => {
return conf.get("github.token");
},
setGithubCredentials: async () => {
const credentials = await inquirer.askGithubCredentials();
const result = _.extend(
{
type: "basic"
},
credentials
);
global.octokit = Octokit({
auth: result
});
},
registerNewToken: async () => {
const status = new Spinner("Authenticating you, please wait...");
status.start();
try {
const response = await global.octokit.oauthAuthorizations.createAuthorization({
scopes: ["user", "public_repo", "repo", "repo:status"],
note: "ginits, the command-line tool for initalizing Git repos"
});
const token = response.data.token;
if (token) {
conf.set("github.token", token);
return token;
} else {
throw new Error(
"Missing Token",
"GitHub token was not found in the response"
);
}
} catch (err) {
throw err;
} finally {
status.stop();
}
}
};
Try something like:
const Octokit = require('#octokit/rest');
module.export = {
getInstance({username, password}) {
return Octokit({
auth: {
username,
password,
},
});
}
}
The PR introducing the auth property shows some other examples of specifying credentials.