I want to start with typescript in my NUXT project.
I tried to rename the db/user.js to db/user.ts
this was my db/user.js file
import { prisma } from "."
import bcrypt from "bcrypt"
export const createUser = (userData) => {
const finalUserData = {
...userData,
password: bcrypt.hashSync(userData.password, 10)
}
return prisma.user.create({
data: finalUserData
})
}
export const getUserByEmail = (email) => {
return prisma.user.findUnique({
where: {
email: email
}
})
}
this is now my db/user.ts file
import { prisma } from "."
import bcrypt from "bcrypt"
export async function createUser(userData: any) {
const finalUserData = {
...userData,
password: bcrypt.hashSync(userData.password, 10)
}
return await prisma.user.create({
data: finalUserData
})
}
export async function getUserByEmail(email: string) {
return await prisma.user.findUnique({
where: {
email: email
}
})
}
When i start my nuxt project with the command "nuxt dev" i will see this error:
I tried the command "npx nuxi typecheck" but i do not get any errors.
Where does the "undefined" error comes from?
And how can i solve it?
Is there any configuration needed for nuxt/typescript?
Related
I have node-fetch installed, but the rest of the files in the project aren't importing it and the tests for them aren't failing
import { IQuery } from 'models/IQuery.interface';
import { NextApiRequest, NextApiResponse } from 'next';
import { handleProxyResponse } from 'utils/handleProxyResponse.util';
import { appendApiRoute, getDefaultHeaders, getLocale } from 'utils/proxy.util';
export const getContentPage = async (locale: string, publicId: string) => {
const headers = getDefaultHeaders();
//fetch is undefined here
const response = fetch(appendApiRoute(`static-content/v1/${locale}/pages/${publicId}`), {
method: 'GET',
headers
});
return response;
};
export default async (request: NextApiRequest, response: NextApiResponse) => {
const currentLocale = getLocale(request);
const { query } = request;
const { slug } = query as IQuery;
const result = await getContentPage(currentLocale, slug);
return handleProxyResponse(result, response);
};
Failing test:
it('should return handledProxyResponse', async () => {
const result = await contentProxy(defaultRequest, response);
expect(result).toEqual(handleProxyResponseReturnValue);
});
May be it is a Issue of version. so you can try by use an external module
`npm install node-fetch`
then import it in your code
import fetch from "node-fetch"
In my nextjs-app I have the following page folder structure
- pages
questions-and-answers
[slug].tsx
inside the [slug].tsx I define the getStaticPaths and getStaticProps:
export const getStaticPaths: GetStaticPaths = async () => {
const pathQuery = await request({
query: `
query AllQaPages {
allQaPages {
slug
}
}`,
variables: {},
})
const paths = pathQuery.allQaPages.map(({ slug }) => ({
params: {
slug: slug,
},
}))
return {
paths,
fallback: false,
}
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const pageRequest = await request({
query: `
query QaPageQuery($slug: String!) {
qaPage(filter: { slug: { eq: $slug } }) {
id
title
slug
qaBlock {
title
id
items {
header
content
id
}
}
}
`
},
variables: { slug: params?.slug },
})
return {
props: {
pageData: pageRequest,
}
}
}
when I run npm run dev it works just fine BUT when I run npm run build, I get the error:
Field 'allQaPages' doesn't exist on type 'Query'
I have no clue why this happens, can someone help me out?
Thanks in advance
I'm writing API using TypeScript and as query builder I use Knex.js.
The problem is - I just can't get any data from database. As I know, I need to create interfaces or something, that is going to represent data structure from database, but it doesn't work. But nothing works, when I trigger endpoint with this function, it seems like infinite pending, no response.
Here is how I was trying to implement this.
import { Knex } from "knex";
import knex from "../src/db/knex";
interface User {
name: string
}
export const getUserById = async (id: string) => {
const query: Knex.QueryBuilder = knex<User>('users');
const data: User[] = await query.select('*');
console.log("data:", data)
};
Or:
...
interface User {
name: string
}
export const getUserById = async (id: string): Promise<User> => {
return await knex.raw('SELECT * FROM users')
};
Also about this users table. I have created it using migration:
import { Knex } from "knex";
export async function up(knex: Knex): Promise<void> {
return knex.schema.createTable('users', (tableBuilder: Knex.CreateTableBuilder) => {
tableBuilder.string('name')
});
}
export async function down(knex: Knex): Promise<void> {
return knex.schema.dropTable('users');
}
PS. Here is my knex.ts and knexfile.ts if problem could be there, because I have no idea, why it happens:
Knex.ts
import path from "path";
import Knex from "knex";
import dotenv from "dotenv";
import knexConfig from "./knexfile";
dotenv.config({
path: path.resolve(path.resolve(), "../../../.env")
})
const enviroment = process.env.NODE_ENV || "development"
const knex = Knex(knexConfig[enviroment]);
export default knex;
// If I want to make/run migration/seed I need to use this and don't forget about --esm
// export default knexConfig;
And here is knexfile.ts
import path from "path";
import dotenv from "dotenv";
dotenv.config({
path: path.resolve(path.resolve(), "../../../.env")
})
interface IKnexConfig {
[key: string]: object
}
const knexConfig: IKnexConfig = {
development: {
client: 'mysql2',
connection: {
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_DATABASE,
},
migrations: {
tableName: 'knex_migrations',
directory: path.resolve() + '/migrations'
},
seeds: {
directory: path.resolve() + '/seeders'
},
debug: true
}
}
export default knexConfig;
I am trying to go to /users/0 from /users page.
In /users/[id].js
export async function getStaticProps(context) {
const { params } = context;
const { id } = params.id;
const transformedUsers = await getData();
const foundUser = transformedUsers.find((user) => user.id === id);
if (transformedUsers.length === 0) {
return {
notFound: true,
};
}
return {
props: {
user: foundUser,
},
};
}
export async function getStaticPaths() {
const transformedUsers = await getData();
const ids = transformedUsers.map((user) => user.id);
const pathsWithParams = ids.map((id) => ({ params: { id } }));
return {
paths: pathsWithParams,
fallback: false,
};
}
After I run the commands npm run build
└ ● /users/[id] 298 B 82.4 kB
I am getting this in the console. But when I start the server with npm start and go to /users/0 i am getting 404 not found.
How to provide paths with getStaticPaths?
I have been following this full-stack tutorial by Ben Awad
and when he added a resolver to the schema, everything went well, but when I tried the exact same code I get the error above. I am using graphql 15.5.1 and type-graphql 1.1.1 with apollo-server-express version 2.25.2. My code looks like this:
import {Query, Resolver} from "type-graphql";
#Resolver()
export class HelloResolver {
#Query(() => Number)
hello() {
return 5;
}
}
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "graphql";
import {HelloResolver} from "./resolvers/hello";
const express = require('express');
const PORT : number = Number(process.env.PORT) || 3000;
const main = async () => {
const apollo = new ApolloServer({
schema: await buildSchema({
// ERROR DUE TO LINE BELOW
resolvers: [HelloResolver],
validate: false,
}),
});
apollo.applyMiddleware({ app });
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});
}
main().catch((e) => {
console.error(e);
});
import { buildSchema } from "graphql";
should be
import { buildSchema } from "type-graphql";
You can see that in the same code linked in the video description.