#nest js auth
Explore tagged Tumblr posts
duomly · 5 years ago
Link
The written version of the video: nest js auth 
This video is the fourth lesson of the Node.js Course, where we are going to create Node js login with PostgreSQL and user authentication. In this course, we are building a banking app backend using Nest.js, Sequelize, PostgreSQL, and Typescript.
0 notes
holytheoristtastemaker · 5 years ago
Link
 One of the most important things which is also often neglected by developers - the performance. One of the key focus area for the 1.0 release was making it blazingly fast ⚡
TypeGraphQL is basically an abstraction layer built on top of the reference GraphQL implementation for JavaScript - graphql-js. To measure the overhead of the abstraction, a few demo examples were made to compare it against the "bare metal" - using raw graphql-js library.
It turned out that in the most demanding cases like returning an array of 25 000 nested objects, the old version 0.17 was even about 5 times slower!
library execution time TypeGraphQL v0.17 1253.28 ms graphql-js 265.52 ms
After profiling the code and finding all the root causes (like always using async execution path), the overhead was reduced from 500% to just 17% in v1.0.0! By using simpleResolvers it can be reduced even further, up to 13%:
execution time graphql-js 265.52 ms TypeGraphQL v1.0 310.36 ms with "simpleResolvers" 299.61 ms with a global middleware 1267.82 ms
Such small overhead is much easier to accept than the initial 500%!  More info about how to enable the performance optimizations in the more complex cases can be found in the docs 📖.
Schema isolation
This is another feature that is not visible from the first sight but gives new possibilities like splitting the schema to public and private ones 👀
In 0.17.x and before, the schema was built from all the metadata collected by evaluating the TypeGraphQL decorators. The drawback of this approach was the schema leaks - every subsequent calls of buildSchema was returning the same schema which was combined from all the types and resolvers that could be find in the metadata storage.
In TypeGraphQL 1.0 it's no longer true! The schemas are now isolated which means that the buildSchema call takes theresolvers array from options and emit only the queries, mutation and types that are related to those resolvers.
const firstSchema = await buildSchema({ resolvers: [FirstResolver], }); const secondSchema = await buildSchema({ resolvers: [SecondResolver], });
So just by modifying the resolvers option we can have different sets of operations exposed in the GraphQL schemas! Proper isolation also makes serverless development easier as it allows to get rid of the "Schema must contain uniquely named types" errors and others.
Directives and extensions
This two new features are two complementary ways to put some metadata about the schema items.
GraphQL directives though the syntax might remind the TS decorators, as "a directive is an identifier preceded by a @ character", but in fact, they are a purely Schema Definition Language feature. Apart from the metadata capabilities, they can also modify the schema and e.g. generate the connection type for pagination purposes. Basically, the looks like this:
type Query { foobar: String! @auth(requires: USER) }
To apply them, we just need to put the @Directive decorator above and supply the string argument, e.g.:
@Resolver() class FooBarResolver { @Directive("@auth(requires: USER)") @Query() foobar(): string { return "foobar"; } }
However, on the other side we have the GraphQL extensions which are the JS way to achieve the same goal. It's the recommended way of putting the metadata about the types when applying some custom logic.
To declare the extensions for type or selected field, we need to use @Extensionsdecorator, e.g.:
@ObjectType() class Foo { @Extensions({ roles: [Role.User] }) @Field() bar: string; }
We can then read that metadata in the resolvers or middlewares, just by exploring the GraphQLResolveInfo object, e.g.:
export const ExtensionsMiddleware: MiddlewareFn = async ({ info }, next) => { const { extensions } = info.parentType.getFields()[info.fieldName]; console.log(extensions?.roles); // log the metadata return next(); };
More info about directives and extensions features can be found in docs 📖
Resolvers and arguments for interface fields
The last thing that was preventing TypeGraphQL from being fully GraphQL compliant thus blocking the 1.0 release - an ability to provide interface fields resolvers implementations and declare its arguments.
Basically, we can define resolvers for the interface fields using the same syntax we would use in case of the @ObjectType, e.g.:
@InterfaceType() abstract class IPerson { @Field() avatar(@Arg("size") size: number): string { return `http://i.pravatar.cc/${size}`; } }
...with only a few exceptions for cases like abstract methods and inheritance, which you can read about in the docs.
More descriptive errors messages
One of the most irritating issues for newcomers were the laconic error messages that haven't provided enough info to easily find the mistakes in the code.
Messages like "Cannot determine GraphQL input type for users" or even the a generic "Generating schema error" were clearly not helpful enough while searching for the place where the flaws were located.
Now, when the error occurs, it is broadly explained, why it happened and what could we do to fix that, e.g.:
Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for argument named 'filter' of 'getUsers' of 'UserResolver' class.
or:
Some errors occurred while generating GraphQL schema: Interface field 'IUser.accountBalance' expects type 'String!' but 'Student.accountBalance' is of type 'Float'
That should allow developers to safe tons of time and really speed up the development 🏎
Transforming nested inputs and arrays
In the previous releases, an instance of the input type class was created only on the first level of inputs nesting.  So, in cases like this:
@InputType() class SampleInput { @Field() sampleStringField: string; @Field() nestedField: SomeNestedInput; } @Resolver() class SampleResolver { @Query() sampleQuery(@Arg("input") input: SampleInput): boolean { return input.nestedField instanceof SomeNestedInput; } }
the nestedField property of input was just a plain Object, not an instance of the SomeNestedInput class. That behavior was producing some unwanted issues, including limited support for inputs and args validation.
Since 1.0 release, it's no longer an issue and all the nested args and inputs are properly transformed to the corresponding input type classes instances, even including deeply nested arrays 
0 notes
tak4hir0 · 6 years ago
Link
In an attempt to dispel the idea that if you have to google stuff you’re not a proper engineer, this is a list of nearly everything I googled in a week at work, where I’m a software engineer with several years’ experience. Obviously these weren’t all googled in a row (although you can probably spot that a few were), but throughout the day. I can’t remember the context of everything I was googling, but hopefully it’ll make you feel a little better next time you have to google something. Mondaynpm react-testing-library - during a React upgrade, looking at dependencies to see latest versions and checking for breaking changes. Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? - said React upgrade then started causing some super fun errors. react-apollo release notes react-apollo/test-utils - tests were throwing some odd errors with our graphQL components. undo a rebase - oops. react testing library apollo "invariant violation" - package upgrades are so much fun! jest silence warnings - don’t judge me, ok? semantic HTML contact details - wanted to check if the tag was relevant here aa contrast checker temporary visual impairment - fact checking for an accessibility talk I was giving that week dominos accessibility - popcorn.gif shame gif - an important part of any presentation Tuesdayjavascript get array of unique dates - if I have an array of Dates, how can I filter them so they are unique? (reduce, naturally, but I can rarely use that without googling it first) date to locale string js date to locale string - after I got a load of Java results alternatives to Moment.js - it’s large group array items by date - more reduce fun sort object keys javascript react fragment keys next link - needed a reminder of how to use the Link component in Next.JS React.Children.only expected to receive a single React element child. visual studio code disable autocomplete html - it keeps autoclosing HTML elements on the same line, and I still can’t switch it off dt dd dl - couldn’t remember what the example use for these was. html nested sections - is it ok to have inside ? display dl in pairs veggie ipsum - the best lorem ipsum generator css keyframes css animate underline text dl vs ul react generating keys - should I use some kind of hash, or should I use data in the props? (I ended up constructing a string with unique timestamp data) css checkbox - can we style checkboxes yet? (no) flexbox center span - it was 17:24 and I was tired by this point grid minmax flexible grid row - I don’t have a whole lot of CSS Grid experience, so I always end up googling a ton with this. grid row height auto cauliflower shortage - someone told me about this and I panicked next.js hooks - we can use them, right? (we can, and I did) Wednesdaycors - today is going to be bleak the corrs - once I hit some CORS errors I decided I needed to make a meme, and I needed to find the perfect image. It took a surprisingly long time. Worth itgit patch trailing whitespace - I was sent a git patch with some whitespace that prevented it from actually patching jsx annotation web api fetch preflight - in my CORS adventures I wanted to read up a bit more about preflight requests. web api fetch origin header discriminated union flow - trying to diagnose problems with my Flow types. whitespace regex - is it \w? (no, that’s a word - it’s \s) regex not letter pat butcher emoji - what can I say, I google important things woman shouting at cat google oauth next.js authentication - sometimes it’s helpful to google stuff to see if anyone has written examples of how to do common flows in the framework or tool that you’re using component displayname - do I need to do this with my higher-order components? nextCookie - starting to mess around with oauth cookies reading cookies in react - there must be a better way than document.cookie js-cookie npm cookies-js npm cookie universal-cookie google oauth cookie 🍪 Thursday"log in with google" localhost - was having all sorts of problems getting this to work httpserverrequest javascript - I have a feeling this was something to do with Flow types nextjs flowtypes - yep, there you go "python-social-auth" react - trying to figure out if the django backend I was working with would play nicely with my React frontend google social login vary header get cookie from 302 google social login cookies - I was having a really fun time with this as you can tell google oauth cookie python-social-auth set-cookie python-social-auth site:stackoverflow.com python-social-auth react site:stackoverflow.com django - I think I gave up at this point and just googled Django because I have literally never used it fetch send cookies testing same origin credentials locally cross origin cookies - spoiler alert: not a thing useState default value "The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when when the request's credentials mode is 'include'. - googling error messages is only second to console.log() as a debugging method useState with empty array react hooks initial state empty array "Provisional headers are shown" - this is where the requests weren’t going through and I couldn’t see what the actual headers being sent were fetch send cookies how to see request headers in chrome fetch not sending cookies Thursday was a whole lot of fun D: Fridayprovisional headers are shown - still at it. sending cookies from localhost - have I mentioned that I hate cookies? editing host file - desperate times (and it didn’t even work) sending cookies with different domain next cookie getinitialprops functional component getting cookies from document js find - to check the usage and return types string contains string methods js - I can’t keep any of these in my head js string methods - 20 mins later js fetch manual cookie django react cookies localhost django react cookies localhost site:stackoverflow.com httponly cookie django httponly async await promise.all nextjs port google appengine node ports next rename static install gcloud cli method patch - couldn’t remember what the HTTP method PATCH does. nextjs env next.js environment variables next js docs editing data with hooks - literally no idea what I was trying to google here but this was past 5pm so I was evidently quite tired react form submit dayjs - I needed the documentation again. What I’m trying to show with all this is that you can do something 100 times but still not remember how to do it off the top of your head. Never be ashamed of googling, even if it seems like the most basic thing you’re looking up. I can never remember how Date works. I’ve built plenty of forms in React but couldn’t remember how onSubmit worked on the Friday evening at 5:30pm. I constantly have to google JS string methods. Cookies are terrible. (Incidentally, we fixed the cookie issue by running everything in a docker container and tunneling with ngrok, so everything’s on the same domain.)
0 notes