Apollo Graph QL: parent is not defined - apollo

So I'm trying to set up my Apollo server and I'm facing this error that says: ReferenceError: parent is not defined which I have passed as parameter to the function.
import { User, Landing, Category } from './resolvers';
export const resolves = {
Query: {
UserDelete: User.UserDelete(parent, args),
UserAuth: User.UserAuth(parent, args),
UserView: User.UserView(parent, args),
UserLandings: User.UserLandings(parent, args),
CategoriesView: Category.CategoriesView(parent, args),
CategoryView: Category.CategoryView(parent, args),
CategoryDelete: Category.CategoryDelete(parent, args),
LandingDelete: Landing.LandingDelete(parent, args),
LandingUp: Landing.LandingUp(parent, args),
LandingDown: Landing.LandingDown(parent, args),
LandingView: Landing.LandingView(parent, args),
LandingsView: Landing.LandingsView(parent, args),
},
Mutation: {
UserRegister: User.UserRegister(parent, args),
UserUpdate: User.UserUpdate(parent, args),
LandingCreate: Landing.LandingCreate(parent, args),
LandingUpdate: Landing.LandingUpdate(parent, args),
CategoryCreate: Category.CategoryCreate(parent, args),
CategoryUpdate: Category.CategoryUpdate(parent, args),
},
};

You're not passing the function arguments properly. Try:
import { User, Landing, Category } from './resolvers';
export const resolves = {
Query: {
UserDelete: (parent,args) => User.UserDelete(parent, args),
UserAuth: (parent,args) => User.UserAuth(parent, args),
etc…

Related

Mock a go-logr and verify the message it logs?

Im using the following go-logr/logr library.
I have a test which needs to pass the logger as parameter and check that it was able to log the data that was sent.
I need to test the function GetConfig:
config, err := GetConfig(FilePath, "ns", logger, "test" )
At the end I need to print some message from the logger in the test
Expect(logger.msg).To(Equal("test"))
My question is how should mock it?
I’ve tried with the following but without success
func NewTestLogger() logr.Logger {
l := &testlogger{
Formatter: funcr.NewFormatter(funcr.Options{}),
}
return logr.New(l)
}
var _ = Describe(“test” action, func() {
It("action configuration with logger", func() {
//var t *testing.T
tl := NewTestLogger()
config, err := GetConfig(kcfgFilePath, "ns", tl, "test")
But Im not able to print the value from the logger, how can I do it right?
Something like
assert.Contains(t, tl.sink.Output, "test")
Should I use the testing package?
update
This is a working version without the assertion.
Not sure what I miss there as I want to assert the data that are coming from the output of the GetConfig 'tl` and get the key and value
This is close to the code I've in prod, how can I make work?
https://go.dev/play/p/XDDkNjkESUw
My Question is how should I assert the following
assert.Contains(t, tl.GetSink().WithName("Output"), "test")
assert.Contains(t, tl.GetSink().WithName("Output"), "message")
assert.Contains(t, tl.GetSink().WithName("Output"), "print something")
I was able to get the data like following, but not sure how to assert the values
The logr.New function accepts any implementation of the LogSink interface - This means you should just implement one that saves the calls onto a slice in-memory instead of printing, and then you can expect that the slice has your log output.
package main
import (
"testing"
"github.com/stretchr/testify/assert"
// ... some extra imports
)
type TestLogger struct {
Output map[string]map[int][]interface{}
r RuntimeInfo
}
func (t *TestLogger) doLog(level int, msg string, keysAndValues ...interface{}) {
m := make(map[int][]interface{}, len(keysAndValues))
m[level] = keysAndValues
t.output[msg] = m
}
func (t *TestLogger) Init(info RuntimeInfo) { t.r = info}
func (t *TestLogger) Enabled(level int) bool {return true}
func (t *TestLogger) Info(level int, msg string, keysAndValues ...interface{}) { t.doLog(level, msg, keysAndValues...) }
func (t *TestLogger) Error(err error, msg string, keysAndValues ...interface{}) { t.doLog(level, msg, append(keysAndValues, err)...) }
func (t *TestLogger) WithValues(keysAndValues ...interface{}) LogSink { return t}
func (t *TestLogger) WithName(name string) LogSink { return t }
func TestLoggerHasOutput(t *testing.T) {
l := &TestLogger{make(map[string]map[int][]interface[]), RuntimeInfo{1}}
tl := logr.New(l)
config, err := GetConfig(kcfgFilePath, "ns", tl, "test")
assert.Contains(t, l.Output, "ns") // you can also test the contents of the output as well
}

How do I stub callbacks of a method?

I am using Firebase Phone Auth in my Flutter project and want to test my auth class. I know how to use when() and .thenAnswer() from Mockito with typical Futures.
I want to test my authentication method, in particular, verificationFailed and verificationCompleted callbacks.
Future<void> getSmsCodeWithFirebase() async {
try {
await _firebaseAuth.verifyPhoneNumber(
phoneNumber: fullPhoneNumber,
timeout: const Duration(seconds: 30),
verificationCompleted: (credential) async {
_firebaseSignIn(credential);
},
verificationFailed: (e) {
errorMessage = 'Error code: ${e.code}';
}
initModelState = DataState.error;
},
codeSent: (String verificationId, int resendToken) {
_firebaseSessionId = verificationId;
initModelState = DataState.idle;
},
codeAutoRetrievalTimeout: (String verificationId) {},
);
} catch (ex) {
errorMessage = 'There was some error';
updateModelState = DataState.error;
}
}
For now I came up with something like this, but I don't understand how to invoke passed callbacks.
test('cant verify phonenumber', () async {
when(mockFirebaseAuth.verifyPhoneNumber(
phoneNumber: any,
codeSent: anyNamed('codeSent'),
verificationCompleted: anyNamed('verificationCompleted'),
verificationFailed: anyNamed('verificationFailed'),
codeAutoRetrievalTimeout: anyNamed('codeAutoRetrievalTimeout')))
.thenAnswer((Invocation invocation) {
// I need to put something here?
});
await authCodeViewModel.getSmsCodeWithFirebase();
expect(authCodeViewModel.initModelState, DataState.error);
});
You're not really asking how to stub callbacks themselves; you're asking how to invoke callbacks for a stubbed method. You'd use captured callback arguments the same as any other captured arguments:
// Sample class with a method that takes a callback.
abstract class Foo {
void f(String Function(int x) callback, int y);
}
#GenerateMocks([Foo])
void main() {
var mockFoo = MockFoo();
mockFoo.f((x) => '$x', 42);
var captured = verify(mockFoo.f(captureAny, any)).captured;
var f = captured[0] as String Function(int);
print(f(88)); // Prints: 88
}
In your case, I think it'd be something like:
test('cant verify phonenumber', () async {
await authCodeViewModel.getSmsCodeWithFirebase();
var captured = verify(mockFirebaseAuth.verifyPhoneNumber(
phoneNumber: any,
codeSent: anyNamed('codeSent'),
verificationCompleted: anyNamed('verificationCompleted'),
verificationFailed: captureNamed('verificationFailed'),
codeAutoRetrievalTimeout: anyNamed('codeAutoRetrievalTimeout')))
.captured;
var verificationFailed = captured[0] as PhoneVerificationFailed;
verificationFailed(FirebaseAuthException());
expect(authCodeViewModel.initModelState, DataState.error);
});
Of course, if you're supplying the callbacks, you don't need to capture them in the first place; you can just invoke them directly yourself.

Why can "rust cookie::CookieJar" get a value through str type

I know that the underlying data structure is a HashSet, but why can the get method use the &str type instead of the cookie structure?
cargo.toml
[dependencies]
cookie = "0.14"
src/main.rs
use cookie::{Cookie, CookieJar};
fn main() {
let mut jar = CookieJar::new();
jar.add(Cookie::new("a", "one"));
jar.add(Cookie::new("b", "two"));
assert_eq!(jar.get("a").map(|c| c.value()), Some("one"));
assert_eq!(jar.get("b").map(|c| c.value()), Some("two"));
jar.remove(Cookie::named("b"));
assert!(jar.get("b").is_none());
}
The authors of cookie-rs implemented the Hash and Borrow trait for the values of the HashSet.
Here's an example mimicking the same behavior:
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::collections::HashSet;
#[derive(Debug, Eq)]
struct Cookie<'a> {
name: &'a str,
id: u64,
}
impl Hash for Cookie<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl PartialEq for Cookie<'_> {
fn eq(&self, other: &Cookie) -> bool {
self.name == other.name
}
}
impl Borrow<str> for Cookie<'_> {
fn borrow(&self) -> &str {
self.name
}
}
fn main() {
let mut cookies: HashSet<Cookie> = HashSet::new();
cookies.insert(Cookie {
name: "example",
id: 42,
});
println!("{:?}", cookies.get("example"));
}
That would give us:
Some(Cookie { name: "example", id: 42 })

Best approach to handle graphql for aws lambda?

I'm following the tutorial https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-lambda-resolvers.html
And have some doubts for using just a switch to handle graphql queries.
Is there a better approach to handle more complicated requests?
The choice is yours as to how to setup lambda within your AppSync API. It is entirely reasonable to have a lambda function per resolver and have a function be responsible for a single resolver. You can alternatively take an approach like the tutorial and use a single function and some lightweight routing code to take care of calling the correct function. Using a single function can often offer some performance benefits because of how lambda's container warming works (esp. for Java & C# where VM startup time can add up) but has less separation of concerns.
Here are some approaches I have taken in the past:
Option 1: JS
This approach uses JavaScript and should feel familiar to those who have run their own GraphQL servers before.
const Resolvers = {
Query: {
me: (source, args, identity) => getLoggedInUser(args, identity)
},
Mutation: {
login: (source, args, identity) => loginUser(args, identity)
}
}
exports.handler = (event, context, callback) => {
// We are going to wire up the resolver to give all this information in this format.
const { TypeName, FieldName, Identity, Arguments, Source } = event
const typeResolver = Resolvers[TypeName]
if (!typeResolver) {
return callback(new Error(`No resolvers found for type: "${TypeName}"`))
}
const fieldResolver = typeResolver[FieldName]
if (!fieldResolver) {
return callback(new Error(`No resolvers found for field: "${FieldName}" on type: "${TypeName}"`), null)
}
// Handle promises as necessary.
const result = fieldResolver(Source, Arguments, Identity);
return callback(null, result)
};
You can then use a standard lambda resolver from AppSync. For now we have to provide the TypeName and FieldName manually.
#**
The value of 'payload' after the template has been evaluated
will be passed as the event to AWS Lambda.
*#
{
"version" : "2017-02-28",
"operation": "Invoke",
"payload": {
"TypeName": "Query",
"FieldName": "me",
"Arguments": $util.toJson($context.arguments),
"Identity": $util.toJson($context.identity),
"Source": $util.toJson($context.source)
}
}
Option 2: Go
For the curious, I have also used go lambda functions successfully with AppSync. Here is one approach that has worked well for me.
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/fatih/structs"
"github.com/mitchellh/mapstructure"
)
type GraphQLPayload struct {
TypeName   string                 `json:"TypeName"`
FieldName string                 `json:"FieldName"`
Arguments map[string]interface{} `json:"Arguments"`
Source     map[string]interface{} `json:"Source"`
Identity    map[string]interface{} `json:"Identity"`
}
type ResolverFunction func(source, args, identity map[string]interface{}) (data map[string]interface{}, err error)
type TypeResolverMap = map[string]ResolverFunction
type SchemaResolverMap = map[string]TypeResolverMap
func resolverMap() SchemaResolverMap {
return map[string]TypeResolverMap{
"Query": map[string]ResolverFunction{
"me": getLoggedInUser,
},
}
}
func Handler(ctx context.Context, event GraphQLPayload) (map[string]interface{}, error) {
// Almost the same as the JS option.
resolvers := resolverMap()
typeResolver := resolvers[event.TypeName]
if typeResolver == nil {
return nil, fmt.Errorf("No type resolver for type " + event.TypeName)
}
fieldResolver := typeResolver[event.FieldName]
if fieldResolver == nil {
return nil, fmt.Errorf("No field resolver for field " + event.FieldName)
}
return fieldResolver(event.Source, event.Arguments, event.Identity)
}
func main() {
lambda.Start(Handler)
}
/**
* Resolver Functions
*/
/**
* Get the logged in user
*/
func getLoggedInUser(source, args, identity map[string]interface{}) (data map[string]interface{}, err error) {
// Decode the map[string]interface{} into a struct I defined
var typedArgs myModelPackage.GetLoggedInUserArgs
err = mapstructure.Decode(args, &typedArgs)
if err != nil {
return nil, err
}
// ... do work
res, err := auth.GetLoggedInUser()
if err != nil {
return nil, err
}
// Map the struct back to a map[string]interface{}
return structs.Map(out), nil
}
// ... Add as many more as needed
You can then use the same resolver template as used in option 1. There are many other ways to do this but this is one method that has worked well for me.
Hope this helps :)
You are not forced to use one single AWS Lambda to handle each request. For this tutorial it's easier for newcomers to get the idea of it, therefore they used this approach.
But it's up to you how to implement it in the end. An alternative would be to create for each resolver a separate AWS Lambda to eliminate the switch and to follow Single Responsibility Principle (SRP).
You can proxy all the queries to a graphql-server
Apollo GraphQL Server provides a very good setup to deploy a GraphQL server in AWS Lambda.

how to return values from actions in emberjs

how to return some value from actions??
I tried this:
var t = this.send("someAction", params);
...
actions:{
someAction: function(){
return "someValue";
}
}
actions don't return values, only true/false/undefined to allow bubbling. define a function.
Ember code:
send: function(actionName) {
var args = [].slice.call(arguments, 1), target;
if (this._actions && this._actions[actionName]) {
if (this._actions[actionName].apply(this, args) === true) {
// handler returned true, so this action will bubble
} else {
return;
}
} else if (this.deprecatedSend && this.deprecatedSendHandles && this.deprecatedSendHandles(actionName)) {
if (this.deprecatedSend.apply(this, [].slice.call(arguments)) === true) {
// handler return true, so this action will bubble
} else {
return;
}
}
if (target = get(this, 'target')) {
Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function');
target.send.apply(target, arguments);
}
}
I had the same question. My first solution was to have the action put the return value in a certain property, and then get the property value from the calling function.
Now, when I need a return value from an action, I define the function that should be able to return a value seperately, and use it in an action if needed.
App.Controller = Ember.Controller.extend({
functionToReturnValue: function(param1, param2) {
// do some calculation
return value;
},
});
If you need the value from the same controller:
var value = this.get("functionToReturnValue").call(this, param1, param2);
From another controller:
var controller = this.get("controller"); // from view, [needs] or whatever
var value = controller.get("functionToReturnValue").call(controller, param1, param2); // from other controller
The first argument of the call() method needs to be the same object that you are running the return function of; it sets the context for the this reference. Otherwise the function will be retrieved from the object and ran from the current this context. By defining value-returning functions like so, you can make models do nice stuff.
Update I just found this function in the API that seems to do exactly this: http://emberjs.com/api/#method_tryInvoke
Look this example:
let t = this.actions.someAction.call(this, params);
Try
var t = this.send("someAction", params);
instead of
vat r = this.send("someAction", params);
Just use #set for set value which you want to return
actions:{
someAction: function(){
// return "someValue";
this.set('var', someValue);
}
}