Why am I getting a different response from programmatically querying this endpoint? - next.js

I am trying to use the createChatInviteLink API method to create a chat invite.
This is the response I get when I try to access it through my browser:
{"ok":true,
"result":{"invite_link":"https://t.me/+4MooeJCENSORED",
"creator":{"id":CENSORED,"is_bot":true,"first_name":"CENSORED","username":"CENSORED"},
"expire_date":1674321925,
"creates_join_request":true,
"is_primary":false,
"is_revoked":false}}
However, none of that useful response shows up when I try the same exact query through my web app. Instead, I get this:
RESPONSE Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://api.telegram.org/botCENSORED/createChatInviteLink?chat_id=CENSORED&expire_date=1674422960&creates_join_request=true',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
Is there a specific part of the response I need to access? Even response.body isn't returning anything useful.
This is the code that tries to fetch the response:
export async function generateGroupInviteURL(
botToken: string,
groupId: string
) {
const fiveMinutesLaterTimestamp = Math.round(new Date().getTime() / 1000) + 300;
fetch(
`https://api.telegram.org/bot${botToken}/createChatInviteLink?chat_id=${groupId}&expire_date=${fiveMinutesLaterTimestamp}&creates_join_request=true`
).then((res) => {
console.log("RESPONSE", res);
});
}
Any ideas on what I'm doing wrong or need to be doing to access the useful part?

Related

Getting error method not allowed and content-type:text/plain

All my routes are working perfectly except CreateGoal. Whenever I add data using the Post method it is giving me the message method not allowed.When I checked the Get method Headers Content-type, it is application/json but when I checked the Post method Headers Content-type, it is text/plain; charset=utf-8. So I think there must be a problem with Content-type. I am not understanding how to solve this problem. I have attached the screenshots for reference.
Screenshots:
Routes:
func Setup(app *fiber.App) {
app.Get("/goals", controllers.GetGoals)
app.Get("/goals/:id", controllers.GetGoal)
app.Post("/goals/add", controllers.CreateGoal)
app.Put("/goals/:id", controllers.UpdateGoal)
app.Delete("/goals/:id", controllers.DeleteGoal)
}
Controllers:
import (
"strconv"
"github.com/gofiber/fiber/v2"
)
type Goal struct {
Id int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}
var goals = []*Goal{
{
Id: 1,
Title: "Read about Promises",
Status: true,
},
{
Id: 2,
Title: "Read about Closures",
Status: false,
},
}
func GetGoals(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(
// "success": true,
// "data": fiber.Map{
// "goals": goals,
// },
goals,
)
}
func CreateGoal(c *fiber.Ctx) error {
type Request struct {
Title string `json:"title"`
}
var body Request
err := c.BodyParser(&body)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"success": false,
"message": "Cannot parse JSON",
"error": err,
})
}
goal := &Goal{
Id: len(goals) + 1,
Title: body.Title,
Status: false,
}
goals = append(goals, goal)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"success": true,
"data": fiber.Map{
"goal": goal,
},
})
}
Your endpoint is /goals/add in the application for POST method. But in Postman you called /goals
In application /goals expecting a GET request. That is why there method is not allowing.

Vue 3: Cannot read property 'id' of null

I want to show list product from api but it shows the error:
Uncaught (in promise) TypeError: Cannot read property 'id' of null
at eval (Home.vue?bb51:103)
at renderList (runtime-core.esm-bundler.js?5c40:6635)
at Proxy.render (Home.vue?bb51:2)
at renderComponentRoot (runtime-core.esm-bundler.js?5c40:1166)
at componentEffect (runtime-core.esm-bundler.js?5c40:5265)......
my product like :
[
{
"id": 1,
"name": "chair",
"categoryId": 12,
"unitId": 2,
"price": 66000000,
"salePrice": 0,
"material": "wood",
"size": "x"
},
]
My code here:
Home.vue file
<ProductCard v-for="product in products" :key="product.id" :product="product" />
ProductCard.vue file
<script>
export default {
name: "ProductCard",
props: {
product: {
type: Object,
required: true,
},
},
};
</script>
ProductService.js file
const apiClient = axios.create({
baseURL: 'http://localhost:8888/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
export default {
getProducts() {
return apiClient.get('/product/get-list-product-by-subcategory')
},
}
When I print out list product in console. It still work.
Does anyone know where is the bug in my code?
Updated:
I try to fix my bug "Cannot read property 'id' of null", Steve's answer although remove my red warning in devtool but not deal my data: my data still not showing up. And I find out my code work by using this.products = response.data.data
ProductService.getProducts()
.then((response) => (this.products = response.data.data))
.catch((error) => console.log("error: " + error));
Explain by myself is:
When console.log(this.products = response)
And I need to use this.products = response.data.data to enter to array
apiClient.get(...)
returns a promise not the actual data from the API call.
You need to add a then. like so
apiClient.get(...).then(response => (this.products = response))
Then when the apiClient.get completes this.products will be populated with the data from the API.
Try this
<ProductCard v-for="product in products" :key="product._id" :product="product" />

How to fix 'RealmObject cannot be called as a function' realm-js error?

In a react-native project using Realm-js, I've just created a clone of the app, integrated all libs, and copied over all src directories.
The app builds installs and runs on Android.
When i go through the authentication flow (which utilizes realm to store auth data), i ultimately get an error:
[ Error: RealmObject cannot be called as a function ]
login function:
async function login(username, password) {
try {
const result = await Api.login({
username: username,
pass: password,
});
const userAuthResult = await Db.updateAuth(result);
setUserAuth(userAuthResult);
} catch (err) {
console.log('[ ERROR ]:', err)
if (!err.message || err.message.includes('Network Error')) {
throw new Error('Connection error');
}
throw new Error('Wrong username or password');
}
}
and ive narrowed down the issue to Db.updateAuth(...)
updateAuth:
export const updateAuth = (params) => {
console.log(' [ HERE 1 ]')
const auth = {
id: params.id,
token: params.token,
refreshToken: params.refresh_token,
tokenExpiresAt: Math.floor(Date.now() / 1000) + 600, //params.expires_at,
federatedToken: params.federatedToken ?? '',
federatedTokenExpiresAt: params.federatedTokenExpiresAt ?? 0,
username: params.username,
name: params.name,
roleName: params.role_name,
roleId: params.role_id,
lastLogin: Math.floor(Date.now() / 1000),
};
console.log(' [ HERE 2 ]')
realm.write(() => {
console.log(' [ HERE 3 ]')
realm.create('Authorizations', auth, 'modified'); // PROBLEM
});
return auth;
};
inspecting the schema, i found theres no federatedToken propereties, yet in the auth update object, there are two. not sure why it wouldnt be throwing an error in the original non-cloned app.
authorizations schema:
AuthorizationsSchema.schema = {
name: 'Authorizations',
primaryKey: 'id',
properties: {
id: 'int',
token: 'string',
refreshToken: 'string',
tokenExpiresAt: 'int',
username: 'string',
name: 'string',
roleName: 'string',
roleId: 'int',
lastLogin: 'int',
},
};
Realm.js (class declaration) -> https://pastebin.pl/view/c903b2e2
from realm instantiation:
let realm = new Realm({
schema: [
schema.AccountSchema,
schema.AuthorizationsSchema,
schema.AvailableServiceSchema,
schema.FederatedTokensSchema,
schema.NoteSchema,
schema.PhotoSchema,
schema.PhotoUploadSchema,
schema.PrintQueueSchema,
schema.ProductSchema,
schema.ReportSchema,
schema.ServicesSchema,
schema.UploadQueueJobSchema,
schema.InvoicesSchema,
schema.TestSchema
],
schemaVersion: 60,
deleteRealmIfMigrationNeeded: true,
//path: './myrealm/data',
});
this logs the 1, 2, and 3 statements. The issue seems to come from the 'problem' line. Im not sure what exactly this error means, as there doesnt seem to be anything in realm's repo about it, and in the app this was cloned from, there was no issue with this line. I can also see other lines are throwing similar errors later on the user flows
Anyone know what this is about? or where i can learn more?
React-native: v64.2
realm-js: 10.6.0 (app cloned from was v10.2.0)
MacOS: 11.3 (M1 architecture)
in order to create you have the first call, the realm.write a method like this.
const storeInDataBase = (res,selectedfile) => {
try{
realm.write(() => {
var ID =
realm.objects(DocumentConverstionHistory).sorted('HistoryID', true).length > 0
? realm.objects(DocumentConverstionHistory).sorted('HistoryID', true)[0]
.HistoryID + 1
: 1;
realm.create(DocumentConverstionHistory, {
HistoryID: ID,
Name:`${selectedfile.displayname}.pdf`,
Uri:`file://${res.path()}`,
Date: `${new Date()}`
});
})
}catch(err){
alert(err.message)
}
}
Here is the schema file
export const DATABASENAME = 'documentconverter.realm';
export const DocumentConverstionHistory = "DocumentConverstionHistory"
export const DocumentConverstionHistorySchema = {
name: "DocumentConverstionHistory",
primaryKey: 'HistoryID',
properties: {
HistoryID: {type: 'int'},
Name: {type: 'string'},
Uri: {type: 'string?'},
Type: {type: 'string?'},
Size: {type: 'string?'},
Date: {type: 'date?'}
}
};

How do I create a custom connect stripe account and pass account id to payment intent method using firebase functions?

I am trying to collect and transfer payments using firebase cloud functions in my react native app. I'm using the stripe.accounts.create and stripe.paymentIntents.create functions as well as library axios. I'm really not too sure how to create the connect account and pass the account id created into the payment intent method. I get the following error in the firebase logs 'code: 'StripeInvalidRequestError: Can only apply an application_fee_amount when the PaymentIntent is attempting a direct payment (using an OAuth key or Stripe-Account header) or destination payment (using transfer_data[destination])'
when trying to run my code below. Can someone please assist? I don't think the connectAcc.id is null since I can see it in my stripe dashboard logs in the response body where the account is created:
Response body
{
"id": "acct_**********U5",
"object": "account",
"business_profile": {
"mcc": "5734",
"name": null,
"product_description": null,
"support_address": null,
"support_email": null,
"support_phone": null,
"support_url": null,
index.js file
const stripe = require('stripe')('**SK_LIVE**');
exports.payWithStripe = functions.https.onRequest((request, response) => {
const connectAcc = stripe.accounts.create({
type: 'custom',
email: 'name#gmail.com',
country: 'GB',
business_type: 'individual',
business_profile: {
mcc: '5734',
url: 'site.com',
},
individual: {
first_name: 'First',
last_name: 'Last',
dob : {
day: 1,
month: 10,
year: 1990
},
email: 'name#gmail.com',
phone: '+44xxxxxxx',
address: {
city: 'city',
country: 'GB',
line1: '1',
line2: 'Street Rd',
postal_code: 'XXX XXX'
}
},
tos_acceptance: {
date: Math.floor(Date.now() / 1000),
ip: request.connection.remoteAddress,
},
capabilities: {
card_payments: {requested: true},
transfers: {requested: true},
},
external_account: {
object: 'bank_account',
country: 'GB',
currency: 'gbp',
account_number: 'xxxxx',
routing_number: 'xxxxx',
accounter_holder_name: 'First Last',
account_holder_type: 'individual',
}
})
stripe.paymentIntents.create({
amount: request.body.amount,
currency: request.body.currency,
payment_method_types: ['card'],
payment_method: request.body.payment_method.id,
application_fee_amount: 20,
on_behalf_of: connectAcc.id,
transfer_data: {
destination: connectAcc.id,
},
confirm: true,
description: 'UniHome'
}
).then((charge) => {
response.send(charge);
})
.catch(err =>{
console.log(err);
})
});
Thanks.
connectAcc is not an account object — it's a Promise. That's what Stripe's SDK returns.
You'd have to resolve the Promise first, like:
let connectAcc = await stripe.accounts.create(...); let id = connectAcc.id or stripe.accounts.create(...).then(function(acct){let id = acct.id;} )

fullcalendar.io send request as JSON object instead of form data

Is there a way to gain further access into the request that Fullcalendar.io sends to the server? Like, are there AJAX options I can modify?
I've examined the header, and it's sending a start and end param, plus the custom_params listed in the example below. However, it is all form data. How do I configure the request to send a JSON object instead of form data?
The documentation is kind of sparse and I am still looking for an example.
Do I use the events as a JSON feed? OR do I use the function(fetchInfo, successCallback, failureCallback)?
events: {
url: '[INTERNAL API / MSSQL]',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function () {
alert('there was an error while fetching events!');
},
// color: 'yellow', // a non-ajax option
// textColor: 'black' // a non-ajax option
},
// events: function(fetchInfo, successCallback, failureCallback) {
// /*is this where I do the AJAX stuff?*/
// fetchInfo = {
// start: "",
// end: "",
// startStr: "",
// endStr: "",
// timeZone: ""
// }
// },

Resources