How to create objects(like in JS) in AWS appsync resolvers? - graphql

I am trying to create this scenario in my resolvers file:
let { data } = await context.client.post(
`https://myendpoint.com/api?action=getUserApiKey&user=${user}&password=${password}&2faCode=${secondFactorToken}`,
);
var userData = {
username: data.user.username,
email: data.user.email,
name: data.user.name,
userId: data.user.userId,
avatarUrl: data.user.avatarUrl,
};
var params = {
key: data.apiKey,
user: userData,
};
return params;
to this in my appsync resolvers:
#if($ctx.result.statusCode == 200)
#set($userData={
$username: $ctx.result.username,
$email: $ctx.result.email,
$name: $ctx.result.name,
$userId: $ctx.result.userId,
$avatarUrl: $ctx.result.avatarUrl,
})
#set($params = {
$key: $ctx.result.apiKey,
$user: $userData,
})
$util.toJson($params);
#else
$utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
What will be the right syntax to perform this in appsync?

Related

Post Error with Apollo Client While Creating a New User

I am running into a POST http://localhost:4000/ 400 (Bad Request) Error.
I am trying to create a new user with the following frontend.
const REGISTER_USER = gql`
mutation Mutation(
$createUser: CreateUserInput!
) {
createUser(createUserInput: $createUserInput){
email
name
token
password
}
}
`
const Register = () => {
const context = useContext(AuthContext)
let navigate = useNavigate()
const [errors, setErrors] = useState([])
function registerUserCallback() {
console.log("Callback hit")
registerUser()
}
const {onChange, onSubmit, values} = useForm(registerUserCallback, {
name: '',
email: '',
password:'',
confirmPassword: '',
})
const [registerUser, {loading}] = useMutation(REGISTER_USER, {
update(proxy, {data: {registerUser: userData}}) {
context.login(userData)
navigate('/Dashboard')
},
onError({graphQLErrors}) {
setErrors(graphQLErrors)
console.log("Error: " + graphQLErrors)
console.log(graphQLErrors)
},
variables: {createUserInput: values}
})
However, the grapQLErrors is not even being console.logged for some reason. When I run the Mutation via Apollo Studio it works. Any information would be great!
Edit: Network Tab Screenshot:
Adding Code for my httpLink:
import { ApolloClient, InMemoryCache, createHttpLink } from "#apollo/client";
import { setContext } from "#apollo/client/link/context";
const httpLink = createHttpLink({
uri: 'http://localhost:4000'
})
const authLink = setContext((_, {headers}) => {
return {
headers: {
...headers,
authorization: localStorage.getItem('token') || ""
}
}
})
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
Edit: createUser Mutation seems to be the issue. This is the Network response error: ["GraphQLError: Unknown argument "createUserInput" on field "Mutation.createUser".","
#Mutation((returns) => User)
async createUser(#Arg('data') data:CreateUserInput, #Ctx() ctx: Context) {
const oldUser = await ctx.prisma.user.findFirst({ where: { email: data.email}})
if(oldUser) {
throw new ApolloError('A user is already registered with the email' + data.email, 'USER_ALREADY_EXISTS')
}
var encryptedPassword = await bcrypt.hash(data.password, 10)
const newUser = await ctx.prisma.user.create({
data: {
name: data.name,
email: data.email,
password: encryptedPassword
}
})
return {token: jwt.sign(newUser, 'supersecret')}
}
Here is a screen shot of my Preview in my Network...I really don't get it.
export class CreateUserInput {
#Field((type) => String)
name: string
#Field((type) => String)
email: string
#Field((type) => String)
password: string

Apollo-client graphql localstate management setup

I'm sitting for 2 days trying to get my setup right. My target is Next.js with ApolloGraphQl for Database request as well as local state management handling.
My problem is the setup for the local state management. Don't know why i'm unable to correctly get it to work. I hope you can help me out.
I pushed my actual status of the project on github using the following repo:
https://github.com/Maetes/apollo-next-local
UPDATE:
it is fine to query and mutate the state when i just call the cache object itself so all is fine. But when i try to trigger a resolver, nothing happens. I'ts like the Apollo-client does not see the typedefs and resolvers.
Here is my useApollo Hook with Client init:
import { IncomingMessage, ServerResponse } from 'http';
import { useMemo } from 'react';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { resolvers } from './localResolvers';
import { typeDefs } from './localTypeDefs';
import {
CREATE_USER,
GET_CURRENT_USER,
SET_CURRENT_USER,
ALL_USERS,
} from './localDocuments';
let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;
export type ResolverContext = {
req?: IncomingMessage;
res?: ServerResponse;
};
function createIsomorphLink(context: ResolverContext = {}) {
if (typeof window === 'undefined') {
const { SchemaLink } = require('apollo-link-schema');
const { schema } = require('../pages/api/index');
return new SchemaLink({ schema, context });
} else {
const { HttpLink } = require('apollo-link-http');
return new HttpLink({
uri: 'http://localhost:3000/api',
credentials: 'same-origin',
});
}
}
function createApolloClient(context?: ResolverContext) {
let cache = new InMemoryCache();
cache.writeData({
data: {
currentUser: {
__typename: 'CurrentUser',
email: '',
nachname: '',
title: '',
id: '',
},
},
});
let client = new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(context),
cache: cache,
typeDefs,
resolvers,
});
// client.writeData({
// data: {
// currentUser: {
// __typename: 'CurrentUser',
// email: '',
// nachname: '',
// title: '',
// id: '',
// },
// },
// });
return client;
}
export function initializeApollo(
initialState: any = null,
// Pages with Next.js data fetching methods, like `getStaticProps`, can send
// a custom context which will be used by `SchemaLink` to server render pages
context?: ResolverContext
) {
const _apolloClient = apolloClient ?? createApolloClient(context);
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState);
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function useApollo(initialState: any) {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
}
This is my typedef file:
import gql from 'graphql-tag';
export const typeDefs = gql`
extend type Query {
getCurrentUser: CurrentUser!
}
type CurrentUser {
email: String!
nachname: String!
title: String!
id: ID!
__typename: String!
}
extend type Mutation {
setCurrentUser(
email: String!
nachname: String!
title: String!
id: ID!
): CurrentUser!
}
`;
this are my resolvers:
import { InMemoryCache } from 'apollo-cache-inmemory';
import { GET_CURRENT_USER } from './localDocuments';
export const resolvers = {
CurrentUser: {
currentUser: (_: {}, { cache }: { cache: InMemoryCache }) => {
console.log('Resolver Query triggered');
// const { user }: any = cache.readQuery({
// query: GET_CURRENT_USER,
// });
const data: any = {};
data.__typename = 'CurrentUser';
return data;
},
getCurrentUser: (_: {}, { cache }: { cache: InMemoryCache }) => {
console.log('Resolver Query triggered');
// const { user }: any = cache.readQuery({
// query: GET_CURRENT_USER,
// });
const data: any = {};
data.__typename = 'CurrentUser';
return data;
},
},
Query: {
getCurrentUser: (_: {}, { cache }: { cache: InMemoryCache }) => {
console.log('Resolver Query triggered');
// const { user }: any = cache.readQuery({
// query: GET_CURRENT_USER,
// });
const data: any = {};
data.__typename = 'CurrentUser';
return data;
},
currentUser: (_: {}, { cache }: { cache: InMemoryCache }) => {
console.log('Resolver Query triggered');
// const { user }: any = cache.readQuery({
// query: GET_CURRENT_USER,
// });
const data: any = {};
data.__typename = 'CurrentUser';
return data;
},
},
Mutation: {
setCurrentUser: (
_: {},
variables: any,
{ cache }: { cache: InMemoryCache }
) => {
const { currentUser }: any = cache.readQuery({ query: GET_CURRENT_USER });
console.log('mutationResolver Triggered');
console.log(
'olduser',
currentUser.email,
currentUser.nachname,
currentUser.title
);
const newUser = {
email: variables.email,
title: variables.title,
nachname: variables.nachname,
__typename: 'CurrentUser',
};
console.log('newUser', newUser);
const erg = cache.writeQuery({
query: GET_CURRENT_USER,
data: newUser,
});
return newUser;
},
},
};
And finaly my Document file for individual input. Please note in the GetCurrentUserQuery query when i change "getCurrentUser" to "currentUser" all is working fine cause apollo targets the raw object itself.
import gql from 'graphql-tag';
//Server
export const ALL_USERS = gql`
query allUsersQuery {
allUsers {
title
nachname
email
id
__typename
}
}
`;
//client
export const GET_CURRENT_USER = gql`
query GetCurrentUserQuery {
getCurrentUser #client(always: true) {
email
nachname
title
__typename
}
}
`;
//Client
export const SET_CURRENT_USER = gql`
mutation SetCurrentUserMutation(
$email: String!
$nachname: String!
$title: String!
$id: String!
) {
setCurrentUser(email: $email, nachname: $nachname, title: $title) #client {
email
title
nachname
id
__typename
}
}
`;
//Server
export const CREATE_USER = gql`
mutation CreateUserMutation(
$email: String!
$nachname: String!
$title: String!
$password: String!
) {
createUser(
email: $email
nachname: $nachname
title: $title
password: $password
) {
__typename
email
nachname
title
password
id
}
}
`;

return the id of the updated document in graphql mongodb

I am new to GraphQL. I have a query which updates a user by his Id. I want to return the id of the document that was updated, but it is returning:
{
"data": {
"editUser": {
"_id": null
}
}
}
GraphQL Query:
mutation {editUser(_id: "5eb801eef0171040044de79f", name: "dd", title:"teacher" , email:"dd#here.com") {
_id
}
}
shema:
const { buildSchema } = require("graphql");
const schema = buildSchema(`type Query {
getUser(_id: ID): User
getUsers: [User]
}
type User {
_id: ID
name: String
title: String
email: String
}
type Mutation {
addUser(name: String, title: String, email: String): User,
editUser(_id: ID, name: String, title: String, email: String): User,
deleteUser(_id: ID): String
}`);
module.exports = { schema };
in resolver.js:
try {
const client = await MongoClient.connect(url);
var dbo = client.db("UserApp");
const myquery = { _id: ObjectId(args._id) };
const updateduser = await dbo
.collection("users")
.updateOne(myquery, { $set: { name: args.name } });
const founduser = await dbo.collection("users").findOne(myquery);
console.log(founduser);
return founduser._id.toString();
} catch (err) {
console.log(err);
}

Graphql - call query in graphqlplayground from connected DB

I'm just starting with graphql and having a few problems calling a basic query in the playground.
I have a server.js
const mongoose = require('mongoose');
require('dotenv').config({ path: 'variables.env' })
const { ApolloServer } = require('apollo-server')
//Monogoose schemas
const Recipe = require('./models/Recipe');
const { typeDefs } = require('./schema');
const { resolvers } = require('./resolvers')
const server = new ApolloServer({
typeDefs,
resolvers
})
// Connect to DB
mongoose
.connect(process.env.MONGO_URI, { autoIndex: false })
.then(() => {
console.log('DB connected')
})
.catch(err => console.error(err))
server.listen().then(({ url }) => {
console.log(`server listening on ${url}`)
})
a schema.js
const gql = require('graphql-tag');
exports.typeDefs = gql`
type Recipe{
_id: ID
name: String!
category: String!
description: String!
instructions: String!
createdDate: String
likes: Int
username: String
}
type Query {
getAllRecipes: [Recipe]
}
`
a resolvers.js
exports.resolvers = {
Query: {
getAllRecipes: async (root, args, { Recipe }) => {
const allRecipes = await Recipe.find()
return allRecipes
}
},
and a mongoose schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const RecipeSchema = new Schema({
name: {
type: String,
required: true
},
category: {
type: String,
required: true
},
description: {
type: String,
required: true
},
instructions: {
type: String,
required: true
},
createdDate: {
type: Date,
default: Date.now
},
likes: {
type: Number,
default: 0
},
username: {
type: String
}
})
module.exports = mongoose.model('Recipe', RecipeSchema)
The server and connection to the DB work and when I open the playground the schema is shown. I have data in the DB
When I run query:
query{
getAllRecipes{
name
}
}
I get an error "Cannot read property 'find' of undefined",
Can anyone see what I'm doing wrong here.
On your resolvers.js file you're expecting Recipe to come from the context argument, but you did not add it anywhere from what I can tell from your snippets.
During the initialization of your ApolloServer instance, you can pass a context property that will be injected on all resolvers:
...
const server = new ApolloServer({
typeDefs,
resolvers,
context: {
Recipe,
},
});
The context property can also be a function that returns an object at the end, in case you want something more elaborated.
For more details on the option and also on others you can pass, see: https://www.apollographql.com/docs/apollo-server/api/apollo-server/.

How to access the context in GraphQL from your resolvers

I just want to send the request to all my resolvers through the context field, but when I access it from one of my resolvers, it returns null.
app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
schema: schema,
context:{token_1:null,test:request},
graphiql:true
})));
These are part of my schema. Firstly I Login to set the token ,but when I want to access the context.token_1 from the other resolver (BuyItems), it returns null.
BuyItems :{
type: UserType,
args: {
name: {type: GraphQLString},
points: {type: GraphQLInt}
},
resolve(parent,args,context){
console.log(context.token_1)
return UserModel.findOneAndUpdate({name:args.name},{points:args.points})
}
},
Login: {
type: AuthType,
args: {
email: {type:GraphQLString},
password: {type:GraphQLString}
},
async resolve(parent,args,context){
const user = await UserModel.findOne({ email: args.email });
if (!user) {
throw new Error('User does not exist on login!');
}
const isEqual = await bcrypt.compare(args.password, user.password);
if (!isEqual) {
throw new Error('Password is incorrect!');
}
const token = jwt.sign(
{ userId: user.id, email: user.email },
'somesupersecretkey',
{ expiresIn: '1h' }
);
context.token_1 = token;
return {tokenExpiration: 1, userId: user.id, token:token}
}
}

Resources