graphql-server-typescript开源项目

我要开发同款
匿名用户2021年11月23日
43阅读
开发技术Java
所属分类大数据、数据查询
授权协议MIT License

作品详情

GraphQL+MongoDBexpressserver(inTypescript)

ThisisjustastarterexampleonhowtobuildaGraphQLserverwithMongoDBdatabaseinTypescript.

Theadvanageofthissolutionisastrongtypechecking,thankstoTypescript,andaeasyGraphQLschemadefinitionusingGraphQLSchemaandGraphQLObjectType.

Thelogicforthedatabasemodelsareinsidethesrc/dbfolderwhilefortheGraphQLtypes,queryandmutationareinsidethesrc/schemafolder.Theschemaisthenbuiltinthesrc/schema/index.tsfile.

FortheautheticationthemethodsetupPassportAuthinthefilesrc/authetication.tswillhandlealltheroutesandaccesstotheusertable.

MoredetailsUsingExpressandGraphQLHTTPServertosetupagraphqlserver.UsingPassportandPassportJSONWebTokenforuserauthenticationwithbcryptforhashingthepasswordduringusercreation.UsingMongoosetointeractwithMongoDBandtakeadvantageofeasymodeldefinitionsandsupportforTypescript.UsingGraphQL.jsdynamicallycreateaGraphQLSchemawithtypes,queryandmutation.UsingTypescripttypecheckingcompilationfordevelopmentandproduction.Install

ThemainExpressAppentrypointissrc/server.ts,itcanbelaunchwiththefollowingcommands:

Fordevelopment(withlivereload)

npmstart

Forproduction(appservedfromdistfolder)

npmrunbuildUsage

InthisexampleweopenaMongoDBconnectiononmongodb://localhost:27017andopentheherosdatabase,soweneedtomakesuremongodserviceisrunningandthedefaultportissetto27017(oryoucanadjusttheparametersinthesrc/server.tsfile).

Runtheexpressserver(withnpmstartornpmbuild).

Weneedthentocreateausertologinwith,wecancreateanadminuserbyvisitingthedebugurlhttps://localhost:3000/add-admin-user.

Wecanthenloginfromtheauthformbyvisitinghttps://localhost:3000/auth(defaultusername:admin,password:admin).

Theloginpagewillrespondwithanauthtoken,ifyouuseaclientwecansaveitandsetitintheheadersforthefollowingrequests,ifyouuseaBrowseryoucanuseanextension(likethisforChrome)tosettheAuthorizationheaderwiththetoken(thetokenneedtobeprecededbyJWTlikeJWTeyJhbGcixxxxxxxxx.

NowyouarereadytoopentheGraphQLinspectorbyvisitinghttps://localhost:3000/graphqlandbrowsetheschemaanddoquery,mutation,etc.

License

MIT

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论