Vercel: This Serverless Function (FUNCTION_INVOCATION_FAILED) - vercel

I have an error that appears when I try to access my link
This Serverless Function has crashed.
Your connection is working correctly.
Vercel is working correctly.
500: INTERNAL_SERVER_ERROR
Code: FUNCTION_INVOCATION_FAILED
ID: cdg1:cdg1::bgdnz-1676557396498-149041f4043b
[GET] /6OzxT
15:07:51:26
2023-02-16T14:07:51.324Z 020abb04-a238-441a-8a1d-5a4fb96d66c3 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: fetch failed","reason":{"errorType":"TypeError","errorMessage":"fetch failed","cause":{"errorType":"ConnectTimeoutError","errorMessage":"Connect Timeout Error","code":"UND_ERR_CONNECT_TIMEOUT","name":"ConnectTimeoutError","message":"Connect Timeout Error","stack":["ConnectTimeoutError: Connect Timeout Error"," at onConnectTimeout (/var/task/vercel/path0/node_modules/undici/lib/core/connect.js:182:24)"," at /var/task/vercel/path0/node_modules/undici/lib/core/connect.js:129:46"," at Immediate._onImmediate (/var/task/vercel/path0/node_modules/undici/lib/core/connect.js:170:9)"," at process.processImmediate (node:internal/timers:471:21)"]},"stack":["TypeError: fetch failed"," at fetch (/var/task/vercel/path0/node_modules/undici/index.js:113:13)"," at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: fetch failed"," at process.<anonymous> (file:///var/runtime/index.mjs:1194:17)"," at process.emit (node:events:525:35)"," at emit (node:internal/process/promises:149:20)"," at processPromiseRejections (node:internal/process/promises:283:27)"," at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
Unknown application error occurred
Runtime.Unknown
I tried to add a try/catch, and normally it should be redirected to the URL (here steellgold.fr)
+page.server.ts (Redirect page) (https://preview.linkfy.fr/6OzxT)
import { PUBLIC_URL, PUBLIC_API_URL } from "$env/static/public";
import type { Link } from "$lib/types/link.type";
import { restRequest } from "$lib/utils/request/request";
import { error, redirect } from "#sveltejs/kit";
import type { PageServerLoad } from "./$types";
// eslint-disable-next-line
export const load = (async({ params }) => {
if (!params.slug) throw redirect(303, PUBLIC_URL);
const data = await restRequest<Link>("get", PUBLIC_URL + "api/link", {
query: {
slug: params.slug
}
}, [], true);
if (!data.success) {
throw error(404, { message: "This link not exist or has been disabled", code: 404 });
}
try {
fetch(PUBLIC_API_URL + "link/" + params.slug);
} catch (e) {
console.error(e);
}
if (!data.data.status) throw error(423, { message: "This link has been disabled", code: 423 });
throw redirect(303, data.data.url);
}) satisfies PageServerLoad;
increment.ts (Fastify route fort increment links)
import { FastifyReply, FastifyRequest } from "fastify";
import { app } from "../..";
import { Link } from "../../types/link";
import { error, success, warn } from "../../utils/logger";
import prisma from "../../utils/prisma";
app.get("/link/:slug", {
handler: async(request: FastifyRequest<{ Params: Link }>, reply: FastifyReply) => {
reply.status(200).send({ message: "Correctly routed received request." });
warn(`[GET] incrementing link with slug /${request.params.slug}.`);
const link = await prisma.link.findUnique({
where: { slug: request.params.slug }
});
if (!link) {
reply.status(404).send({ error: "Link not found" });
error(`[404] Link with slug /${request.params.slug} not found.`);
return;
}
await prisma.link.update({
where: { slug: request.params.slug },
data: { clicks: link.clicks + 1 }
});
success(`[200] Link with slug /${request.params.slug} incremented by 1.`);
return reply.status(200).send({
message: "Link incremented successfully."
});
}
});```
All codes is open-source: https://github.com/Steellgold/Linkfy or https://github.com/Steellgold/LinkfyAPI if you want

Related

Nuxt 3 - Server not ready on mount, Volar engine confused

I have two issues that may or may not be related.
Overview
Folder Structure
pages
|---user.vue
server
|---api
|---profile.get.ts
|---profile.post.ts
The tech is Nuxt3 using the server and Supabase.
profile.get.ts
import { serverSupabaseClient, serverSupabaseUser } from "#supabase/server"
import { Database } from "~~/types/supabase"
export default defineEventHandler(async (event) => {
try {
const supabase = serverSupabaseClient<Database>(event)
const user = await serverSupabaseUser(event)
const query = getQuery(event)
const { data, error } = await supabase.from('profiles').select('*').eq('email', query.email).single()
if (error) throw { status: error.code, message: error.message }
return { displayName: data.display_name, avatarUrl: data.avatar_url }
} catch (err) {
console.error('Handled Error:', err)
}
})
profile.post.ts
import { serverSupabaseClient } from "#supabase/server"
import { Database } from "~~/types/supabase"
export default defineEventHandler(async (event) => {
const supabase = serverSupabaseClient<Database>(event)
const { displayName, avatarUrl, email }: { displayName: string, avatarUrl: string, email: string } = await readBody(event)
const { error } = await supabase.from('profiles').update({ display_name: displayName, avatar_url: avatarUrl }).match({ email })
if (error) throw new Error(error.message)
return { status: 200 }
})
user.vue Snippet
onMounted(() => {
setTimeout(() => {
getProfile()
}, 100) // Fails when around 50 or less
})
async function getProfile() {
const { data, error } = await useFetch('/api/profile', { method: 'GET', params: { email: user.value?.email } })
console.log(data.value)
console.log(error.value)
displayName.value = data.value!.displayName || ''
avatarUrl.value = data.value!.avatarUrl || ''
}
Problem 1
When user.vue mounts, I want to call my Nuxt API (profile.get.ts) and fetch user data (display name, avatar url) from the Supabase database. However, I receive this error when fetching on mount: FetchError: 404 Cannot find any route matching /api/profile. (/api/profile). However, if I use setTimeout to 100ms, it fetches fine. That makes me think the API server is simply not ready, but the documentation doesn't mention that and encourages fetching during lifecycle.
Problem 2
Volar seems to be confused about the typing of data from getProfile().
Property 'displayName' does not exist on type '{ status: number; } | { displayName: string | null; avatarUrl: string | null; }'.
Property 'displayName' does not exist on type '{ status: number; }'.ts(2339)
However, this is the typing from profile.post.ts even though I'm using profile.get.ts.
Current Behavior
Without setTimeout at 100ms or greater, it will fail with the 404 message
With setTimeout at 100ms or greater, or with getProfile() called from a button, there is no issue, even with the TypeScript errors, etc.
Desired Behavior
TypeScript correctly recognizes the proper endpoint (profiles.get.ts since I'm calling it with get)
Data can be fetched on mount from the API without the use of setTimeout

NextJS API route error "TypeError: res.status is not a function"

I created a simple api endpoint named getFeed which is supposed to get feed content from Sanity CMS. But unexpectedly the endpoint is throwing an error "res.status is not a function". I know there is a similar question asked here , but in my case the api endpoint file is stored in the supposed pages/api directory. Here is the code snippet below.
import { NextApiResponse } from 'next'
import { client } from '../../lib/sanity/sanity'
export default async function getFeed(res: NextApiResponse) {
try {
const feeds = await client.fetch(
`*[_type == "post"]
{
_createdAt,
title,
description,
picture,
postDocId,
postedByUserId,
postedByUserName,
postedByUserImage
}`
)
return res.status(200).json({ feeds })
} catch (error) {
return res.status(500).json({ message: "Couldn't get post feed:\n", error })
}
}
Here is my folder structure
What am I doing wrong??
Try to specify also the req parameter and add a type to the response:
import { NextApiRequest, NextApiResponse } from 'next'
interface Data {
message?: string;
feeds?: <type-of-feeds>[];
}
export default async function getFeed(req: NextApiRequest, res: NextApiResponse<Data>) { ... }

Vue: Unhandled promise rejection Error: Request failed with status code 404?

My API url is http://localhost:5000/api/user/list, data shows as:
[{"Id":1,"name":"Michael","pwd":"123456","age":0,"birth":"2018-01-05","addr":"''"},{"Id":2,"name":"Jack","pwd":"123512616","age":0,"birth":"2018-01-05","addr":"''"}]
User.vue
import axios from 'axios';
export default {
data() {
return {
filters: {
name: ''
},
loading: false,
users: [
]
}
},
methods: {
getUser: function () {
axios.get('http://localhost:5000/api/user/list', function (data) {
this.$set('users', data);
})
}
},
mounted() {
this.getUser();
}
});
The error is :
Unhandled promise rejection Error: Request failed with status code 404(…)
How can I fix it?
You should register a handler for your axios request.
Currently you are using settings argument as a handler.
axios.get('http://localhost:5000/api/user/list').then(function (response) {
// this is your handler.
})
Btw, make sure you are not requesting via CORS.
In my case there was a spelling mistake in URL string. It is fixed after that correction.

Ember errors.add inside catch after save causes form button to not respond

My server responds with a 400 status if a book title already exists. The ember app catches the error and does a errors.add with the attribute name and error detail. For some reason when a receive the 400 when I change the title the form submit button is dead. I found that when I eliminate the errors.add line the problem goes away.
Here is my action:
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Route.extend({
model() {
return this.store.createRecord('book');
},
setupController: function(controller, model) {
controller.set('book', model);
controller.set('errors', DS.Errors.create());
},
actions: {
createBook: function(book) {
var _this = this;
var errors = _this.controllerFor('books.new').get('errors');
book.save().then(function(book) {
_this.transitionTo('books.book', book);
}).catch(function(response) {
response.errors.forEach(function(error) {
var attribute = error.source.pointer.split('/')[3];
//This line causes the problem---> errors.add(attribute, error.detail);
});
});
}
}
});
This is the response:
res.status(400).send({
errors: [
{
status: "400",
source: { pointer: '/data/attributes/title' },
title: "Invalid Attribute",
detail: 'must be unique'
}
]
});

Ember-Simple-Auth and Torii

I am having a problem in connecting ember-simple-auth and torii in order to do a facebook authentication.
I have in my config/environment.js:
torii: {
providers: {
'facebook-oauth2': {
apiKey: 'my_api_key'
}
}
}
package.json:
"ember-simple-auth": "1.0.1",
"torii": "0.6.1"
controllers/application.js:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Controller.extend(ApplicationRouteMixin, {
session: Ember.inject.service('session'),
torii: Ember.inject.service(),
actions: {
authenticateWithFacebook: function(){
this.get('session').authenticate(
'simple-auth-authenticator:torii',
'facebook-oauth2'
).then(
function(data) {
alert('SUCCESS ' + data);
},
function(error) {
alert('There was an error when trying to sign you in: ' + error);
}
);
}
}
});
app/authenticators/torii.js:
import ToriiAuthenticator from 'ember-simple-auth/authenticators/torii';
export default ToriiAuthenticator.extend({
torii: Ember.inject.service()
});
Although I can connect with facebook using just torii, this example fails with the following error:
Uncaught Error: Assertion Failed: No authenticator for factory "simple-auth-authenticator:torii" could be found!
Any ideas? I use the latest ember-cli version.