how to fix octokit.authenticate() is deprecated - node.js

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.

Related

telegram api signup return PHONE_CODE_INVALID

my code:
const { Api, TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");
const { Logger } = require("telegram/extensions");
const apiId = 22;
const apiHash = "333333";
const phoneNumber = "9996627328";
const phoneCode = "22222";
const createClient = async (stringSession) => {
const session = new StringSession(stringSession);
const options = { connectionRetries: 5, baseLogger: new Logger("debug") };
const client = new TelegramClient(session, apiId, apiHash, options);
client.session.setDC(2, "149.154.167.40", 443);
await client.connect();
return client;
};
const getLoginCodeCommand = (phoneNumber) => {
const settings = new Api.CodeSettings();
const args = { phoneNumber, apiId, apiHash, settings };
return new Api.auth.SendCode(args);
};
(async () => {
const client = await createClient("");
const response = await client.invoke(getLoginCodeCommand(phoneNumber));
console.log('responseļ¼š', response);
const { phoneCodeHash } = response;
const result22 = await client.invoke(
new Api.auth.SignUp({
phoneNumber: phoneNumber,
phoneCodeHash: phoneCodeHash,
firstName: "liu",
lastName: "some",
})
);
console.log("RESULT22", result22);
})();
response:
/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28
return new RPCBaseErrors_1.RPCError(rpcError.errorMessage, request, rpcError.errorCode);
^
RPCError: 400: PHONE_CODE_INVALID (caused by auth.SignUp)
at RPCMessageToError (/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28:12)
at MTProtoSender._handleRPCResult (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:517:58)
at MTProtoSender._processMessage (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:442:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async MTProtoSender._recvLoop (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:418:17) {
code: 400,
errorMessage: 'PHONE_CODE_INVALID'
}
No matter how you adjust it, the phone code is always invalid
The correct result should be direct registration success.
I haven't been able to find the problem because of what? Please help me to see why?
doc link: https://gram.js.org/tl/auth/SignUp#authsignup

Cypress automation test continuously generating authentication token while doing authentication test in SharePoint Sites

All the test is passing successfully but still the cypress test is generating token continuously.
cypress.config.js
const { defineConfig } = require("cypress");
const spauth = require("node-sp-auth");
let getLoginTest = async () => {
const username = "****#****.com";
const password = "******";
const pageUrl = "https://*****.sharepoint.com"
// Connect to SharePoint
const data = await spauth.getAuth(pageUrl, {
username: username,
password: password
});
return data;
};
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
on('task', {
// deconstruct the individual properties
async getLogin() {
try {
const res = await getLoginTest();
return res;
} catch (error) {
return error;
}
}
});
},
},
});
Below I have mentioned the tests case which I have created."Testspec.cy.js"
// <reference types="cypress" />
require('cypress-xpath')
describe('SharePoint Authentication', () => {
beforeEach(() => {
cy.task("getLogin").then(token => {
cy.visit({
method: "GET",
url: "https://*****.sharepoint.com/SitePages/Home.aspx",
headers: token.headers
});
});
});
it('SharePoint Authentication Test', () => {
cy.xpath('//*[contains(text(),"Customer Dashboard")]').should('be.visible');
cy.get('.alphabet > :nth-child(3)').click();
cy.contains('Leader').click();
});
});
Test Screen
Here is the screenshot of the cypress test

Why createAsyncThunk is not returning error message?

The url I put inside axios.get is a wrong url. I am expecting an error message through action.error.message in the reducer section. But it's not returning any message despite the fetch request being failed. The code as follows:
usersSlice.js
const createSlice = require("#reduxjs/toolkit").createSlice;
const createAsyncThunk = require("#reduxjs/toolkit").createAsyncThunk;
const axios = require("axios");
const initialState = {
loading: false,
users: [],
error: "",
};
const fetchUsers = createAsyncThunk("users/fetchUsers", () => {
return axios
.get("https://jsonplaceholder.typicodeasdf.com/users")
.then((res) => console.log(res.data.map((user) => user.name)));
});
const usersSlice = createSlice({
name: "users",
initialState,
extraReducers: (builder) => {
builder.addCase(fetchUsers.pending, (state) => {
state.loading = true;
});
builder.addCase(fetchUsers.fulfilled, (state, action) => {
state.loading = false;
state.users = action.payload;
console.log("success");
});
builder.addCase(fetchUsers.rejected, (state, action) => {
state.loading = false;
state.users = [];
state.error = action.error.message;
console.log("failed");
});
},
});
module.exports = usersSlice.reducer;
module.exports.fetchUsers = fetchUsers;
store.js
const configureStore = require("#reduxjs/toolkit").configureStore;
const reduxLogger = require("redux-logger");
const usersSlice = require("./Features/users/userSlice");
const store = configureStore({
reducer: {
usersSlice: usersSlice,
},
});
module.exports = store;
index.js
const { fetchUsers } = require("./App/Features/users/userSlice.js");
const store = require("./App/store.js");
console.log("intial state", store.getState());
const unsubscribe = store.subscribe(() =>
console.log("updated state", store.getState())
);
store.dispatch(fetchUsers());
unsubscribe();
output
intial state { usersSlice: { loading: false, users: [], error: '' } }
updated state { usersSlice: { loading: true, users: [], error: '' } }
failed
Note
In the output I am expecting
updated state { usersSlice: { loading: false, users: [], error: 'some error message' } }
The thunk function in RTK has a built-in method to return an error message if the promise is rejected. I was actually willing to get that message. However, I resolved the problem. Instead of returning the data I actually console logged it. And completely forgot to fix it.
const fetchUsers = createAsyncThunk("users/fetchUsers", () => {
return axios
.get("https://jsonplaceholder.typicodeasdf.com/users")
**.then((res) => console.log(res.data.map((user) => user.name)));**
});

Why am i getting this discordAPIerror

so i was trying to make a discord bot and it is giving me this error:
DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (C:\Users\Admin\Desktop\bot\node_modules#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:287:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\Admin\Desktop\bot\node_modules#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (C:\Users\Admin\Desktop\bot\node_modules#discordjs\rest\dist\lib\REST.cjs:52:22)
at async Client.client.handleCommands (C:\Users\Admin\Desktop\bot\src\functions\handlers\handleCommands.js:28:9) {
rawError: {
code: 50035,
errors: { '0': [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v9/applications/1009341661572243516/guilds/688019305299706004/commands',
requestBody: { files: undefined, json: [ [Object], [Object] ] }
}
the code is as follows:
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith('.js'));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
client.commands.set(command.data.name, command);
commandArray.push(command, command.data.toJSON());
}
}
const clientId = '1009341661572243516';
const guildId = '688019305299706004';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application(/) commands.');
} catch (error) {
console.error(error);
}
};
};
command file:
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Returns a ping"),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true,
});
const newMessage = `API Latency: ${client.ws.ping}\n Client Ping: ${
message.createdTimestamp - interaction.createdTimestamp
}`;
await interaction.reply({
content: newMessage,
});
},
};
The error is from your commandArray, you are pushing 2 elements but as you can see in the documentation (https://discordjs.guide/interactions/slash-commands.html#guild-commands ), we just need to pass command.data.toJSON() and not command, command.data.toJSON(). I had the same issue and it worked for me.
Here is the right formated code
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith('.js'));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
client.commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
}
}
const clientId = '1009341661572243516';
const guildId = '688019305299706004';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application(/) commands.');
} catch (error) {
console.error(error);
}
};
};

cannot mock a fetch call with `fetch-mock-jest 1.5.1` lib

I'm trying to mock a fetch call using thisfetch-mock-jest but it the code still trys to go to the remote address and eventually fail with error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: getaddrinfo ENOTFOUND some.domain.io].
Here the the test code
import { AppConfig } from '#backstage/config';
import { loadConfig } from './loader';
import mockFs from 'mock-fs';
import fetchMock from 'fetch-mock-jest';
describe('loadConfig', () => {
beforeEach(() => {
fetchMock.mock({
matcher: '*',
response: `app:
title: Example App
sessionKey: 'abc123'
`
});
});
afterEach(() => {
fetchMock.mockReset();
});
it('load config from remote path', async () => {
const configUrl = 'https://some.domain.io/app-config.yaml';
await expect(
loadConfig({
configRoot: '/root',
configTargets: [{ url: configUrl }],
env: 'production',
remote: {
reloadIntervalSeconds: 30,
},
})
).resolves.toEqual([
{
context: configUrl,
data: {
app: {
title: 'Example App',
sessionKey: 'abc123',
},
},
},
]);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
function defer<T>() {
let resolve: (value: T) => void;
const promise = new Promise<T>(_resolve => {
resolve = _resolve;
});
return { promise, resolve: resolve! };
}
});
loadConfig has the fetch code that I'm trying to mock.
export async function loadConfig(
options: LoadConfigOptions,
): Promise<AppConfig[]> {
const loadRemoteConfigFiles = async () => {
const configs: AppConfig[] = [];
const readConfigFromUrl = async (remoteConfigProp: RemoteConfigProp) => {
const response = await fetch(remoteConfigProp.url);
if (!response.ok) {
throw new Error(
`Could not read config file at ${remoteConfigProp.url}`,
);
}
remoteConfigProp.oldETag = remoteConfigProp.newETag ?? undefined;
remoteConfigProp.newETag =
response.headers.get(HTTP_RESPONSE_HEADER_ETAG) ?? undefined;
remoteConfigProp.content = await response.text();
return remoteConfigProp;
};
.......
return configs;
}
let remoteConfigs: AppConfig[] = [];
if (remote) {
try {
remoteConfigs = await loadRemoteConfigFiles();
} catch (error) {
throw new Error(`Failed to read remote configuration file, ${error}`);
}
}
........ do some stuff with config then return
return remoteConfigs;
}
The config is a yaml file, that eventually gets parsed and converted into config object.
Any idea why is it failing to mock the fetch call?
replaced
import fetchMock from 'fetch-mock-jest';
with
const fetchMock = require('fetch-mock').sandbox();
const nodeFetch = require('node-fetch');
nodeFetch.default = fetchMock;
and fetchMock.mockReset(); with fetchMock.restore();

Resources