├── .github └── workflows │ └── test.yaml ├── .gitignore ├── LICENSE ├── README.md ├── api ├── errors.go ├── request.go ├── server.go └── server_test.go ├── cmd ├── example.go ├── generate.go ├── init.go └── root.go ├── codegen ├── config │ ├── config.go │ └── config_test.go ├── generator │ ├── executer_generator.go │ ├── field_resolver_generator.go │ ├── generator.go │ ├── init.go │ ├── middleware_generator.go │ ├── model_generator.go │ ├── mutation_resolver_generator.go │ ├── query_resolver_generator.go │ └── webhook_generator.go ├── graphql │ ├── dgraph.go │ ├── schema.go │ └── types.go ├── parser │ └── parser.go └── rewriter │ └── rewriter.go ├── dev.Dockerfile ├── docker-compose.yml ├── dson └── dson.go ├── examples ├── lambda │ ├── generated │ │ └── generated.go │ ├── model │ │ ├── cyclic_model.go │ │ └── models_gen.go │ └── resolvers │ │ ├── field.resolver.go │ │ ├── middleware.resolver.go │ │ ├── mutation.resolver.go │ │ ├── query.resolver.go │ │ ├── resolver.go │ │ └── webhook.resolver.go ├── models │ └── credentials.go ├── server.go └── test.graphql ├── go.mod ├── go.sum ├── internal ├── mod.go ├── mod_test.go ├── packages.go └── packages_test.go ├── lambda.yaml ├── main.go └── test_resources ├── faulty1.yaml ├── faulty2.yaml ├── faulty3.yaml ├── faulty4.yaml └── faulty5.yaml /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Run Tests 3 | jobs: 4 | test: 5 | strategy: 6 | matrix: 7 | go-version: [1.16.x] 8 | os: [ubuntu-latest, macos-latest, windows-latest] 9 | name: run tests 10 | runs-on: ${{ matrix.os }} 11 | steps: 12 | - name: Install Go 13 | uses: actions/setup-go@v2 14 | with: 15 | go-version: ${{ matrix.go-version }} 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | - name: Test 19 | run: go test ./... -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | dgraph-lambda-go 18 | server.go -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dgraph-lambda-go 2 | 3 | Go Library written to build Dgraph Lambda servers as an alternative to the [Dgraph JS Lambda Server](https://github.com/dgraph-io/dgraph-lambda) 4 | 5 | It is currently in **development**! Please create an issue if something is not working correctly. 6 | 7 | If you would like to support me please visit my [:coffee:](https://ko-fi.com/schartey) 8 | 9 | ## Getting started 10 | 11 | - Create project ```go mod init``` 12 | - To install dgraph-lambda-go run the command ```go get -d github.com/schartey/dgraph-lambda-go``` in your project directory. 13 | - Then initialize the project by running ```go run github.com/schartey/dgraph-lambda-go init```. 14 | - Set path to your graphql schema in lambda.yaml 15 | - Generate types and resolvers ```go run github.com/schartey/dgraph-lambda-go generate``` 16 | - Implement your lambda resolvers 17 | - Run your server ```go run server.go``` 18 | 19 | 20 | ## Configuration 21 | 22 | When first initializing the lambda server it will generate a basic lambda.yaml file with the following configuration: 23 | 24 | schema: 25 | - ../trendgraph/dgraph/*.graphql 26 | 27 | exec: 28 | filename: lambda/generated/generated.go 29 | package: generated 30 | 31 | model: 32 | filename: lambda/model/models_gen.go 33 | package: model 34 | 35 | force: 36 | - "Home" 37 | 38 | autobind: 39 | - "github.com/schartey/dgraph-lambda-go/examples/models" 40 | 41 | resolver: 42 | dir: lambda/resolvers 43 | package: resolvers 44 | filename_template: "{resolver}.resolver.go" # also allow "{name}.resolvers.go" 45 | 46 | server: 47 | standalone: true 48 | 49 | ### Schema 50 | 51 | A list of graphql schema files using glob. This is probably only one file when using DGraph. 52 | 53 | ### Exec 54 | 55 | This option allows you to select a file path where generated code should go that should NOT be edited. 56 | 57 | ### Model 58 | 59 | This option allows you to define a file path where the generated models should be placed. 60 | 61 | ### Force 62 | 63 | Force generation of specific models 64 | 65 | ### Autobind 66 | 67 | You might have some predefined models already. Here you can define a list of packages in which models can be found that should be used instead of generating them. Models you add within the generated model folder will be autobound automatically. 68 | 69 | ### Resolver 70 | 71 | Define a folder and package name for the generated resolvers. The filename_template can currently only be {resolver}.resolver.go, but I want to allow resolver generation based on name as well in the future. Using {resolver}.resolver.go will generate a fieldResolver.go, queryResolver.go, mutationResolver.go, webhookResolver.go and middlewareResolver.go file where each type of resolver will reside in. 72 | 73 | ### Server 74 | 75 | On initialization a server.go file is generated from which you can start the server. With standalone set to false you can add custom routes to the http server. 76 | 77 | 78 | ## Generating resolvers 79 | 80 | This framework is able to generate field, query, mutation and webhook resolvers. These will automatically be detected in the graphql schema file. 81 | To generate middleware you have to use comments within the schema. For example: 82 | 83 | ### Type Fields: 84 | ```graphql 85 | type User @lambdaOnMutate(add: true, update: true, delete: true) { 86 | id: ID! 87 | username: String! 88 | """ 89 | @middleware(["auth"]) 90 | """ 91 | secret: string @lambda 92 | } 93 | ``` 94 | ### Queries 95 | ```graphql 96 | type Query { 97 | """ 98 | @middleware(["auth"]) 99 | """ 100 | randomUser(seed: String): User @lambda 101 | } 102 | ``` 103 | 104 | ### Mutations 105 | ```graphql 106 | type Mutation { 107 | """ 108 | @middleware(["auth"]) 109 | """ 110 | createUser(input: CreateUserInput!): User @lambda 111 | } 112 | ``` 113 | 114 | 115 | ## Implementing resolvers 116 | 117 | Here are implementations from the above mentioned schema examples. 118 | ### Field Resolver 119 | 120 | ```golang 121 | func (f *FieldResolver) User_secret(ctx context.Context, parents []string, authHeader api.AuthHeader) ([]string, error) { 122 | var secrets []string 123 | for _, userParent := range userParents { 124 | secrets = append(secrets, fmt.Sprintf("Secret - %s", userParent.Id)) 125 | } 126 | return secrets, nil 127 | } 128 | ``` 129 | 130 | ### Query Resolver 131 | 132 | ```golang 133 | func (q *QueryResolver) Query_randomUser(ctx context.Context, seed string, authHeader api.AuthHeader) (*model.User, error) { 134 | nameGenerator := namegenerator.NewNameGenerator(seed) 135 | name := nameGenerator.Generate() 136 | 137 | user := &model.User{ 138 | Id: "0x1", 139 | Username: name, 140 | } 141 | return user, nil 142 | } 143 | ``` 144 | 145 | ### Mutation Resolver 146 | 147 | ```golang 148 | func (q *MutationResolver) Mutation_createUser(ctx context.Context, input *model.CreateUserInput, authHeader api.AuthHeader) (*model.User, error) { 149 | user := &User{ 150 | Id: "0x1", 151 | Username: createUserInput.Username, 152 | } 153 | return user, nil 154 | } 155 | ``` 156 | 157 | ### Webhook Resolver 158 | 159 | ```golang 160 | func (w *WebhookResolver) Webhook_User(ctx context.Context, event api.Event) error { 161 | // Send Email 162 | return nil 163 | } 164 | ``` 165 | 166 | ### Middleware Resolver 167 | 168 | ```golang 169 | func (m *MiddlewareResolver) Middleware_auth(md *api.MiddlewareData) error { 170 | // Check Token 171 | valid := true //false 172 | if valid { 173 | md.Ctx = context.WithValue(md.Ctx, "logged_in", "true") 174 | return nil 175 | } else { 176 | return errors.New("Token invalid!") 177 | } 178 | } 179 | ``` 180 | 181 | ## Inject custom dependencies 182 | 183 | Typically you want to at least inject a graphql/dql client into your resolvers. To do so just add your client to the Resolver struct 184 | ```golang 185 | // Add objects to your desire 186 | type Resolver struct { 187 | Dql *dgo.Dgraph 188 | } 189 | ``` 190 | and pass the client to the executor in your generated server.go file 191 | ```golang 192 | dql := NewDqlClient() 193 | resolver := &resolvers.Resolver{ Dql: dql} 194 | executer := generated.NewExecuter(resolver) 195 | ``` 196 | Then you can access the client in your resolvers like this 197 | ```golang 198 | func (q *QueryResolver) Query_randomUser(ctx context.Context, seed string, authHeader api.AuthHeader) (*model.User, error) { 199 | // Oversimplified 200 | vars := map[string]string{"$uid": uid} 201 | query := ` 202 | query findUser($uid: string) { 203 | findUser(func: uid($uid)) { 204 | id: uid 205 | } 206 | }` 207 | 208 | res, err := s.dql.NewReadOnlyTxn().QueryWithVars(ctx, query, vars) 209 | if err != nil { 210 | return nil, err 211 | } 212 | 213 | // You can use the provided dql json unmarshaller 214 | var findUserResult struct { 215 | FindUser []model.User `dql:"findUser"` 216 | } 217 | dson.Unmarshal(res.GetJson(), &findUserResult) 218 | 219 | return &findUserResult.FindUser[0], nil 220 | } 221 | ``` 222 | 223 | ## Notes 224 | - Working with Cyclic types 225 | If you have types in your schema with @hasInverse and one of them should not be generated, but you provide your own (see Autobind), then you should put that type declaration into the generation folder with the models_gen.go file. Otherwise the imports will be cyclic and Golang does not like that. See example under examples/lambda/model/cyclic_model.go 226 | 227 | - When using graphql to generate the dgraph schema, type fields are prefixed with the type (Type.field). dgraph-lambda-go provides a json parser that uses the tag "dql" and is able to convert dql query results into the generated models using jsoniter. Example: 228 | 229 | Schema 230 | ```graphql 231 | type User { 232 | id: ID! 233 | username: String! 234 | } 235 | ``` 236 | 237 | Model 238 | ```golang 239 | type User struct { 240 | Id string `json:"id" dql:"uid"` 241 | Username string `json:"username" dql:"User.username"` 242 | } 243 | ``` 244 | 245 | Code 246 | ```golang 247 | vars := map[string]string{"$uid": uid} 248 | query := ` 249 | query findUser($uid: string) { 250 | findUser(func: uid($uid)) { 251 | id: uid 252 | } 253 | }` 254 | 255 | res, err := s.dql.NewReadOnlyTxn().QueryWithVars(ctx, query, vars) 256 | if err != nil { 257 | return nil, err 258 | } 259 | 260 | // ======== Here we use the dson unmarshaller ====== 261 | var findUserResult struct { 262 | FindUser []model.User `dql:"findUser"` 263 | } 264 | dson.Unmarshal(res.GetJson(), &findUserResult) 265 | // ================================================= 266 | 267 | return &findUserResult.FindUser[0], nil 268 | ``` 269 | ## Known Issues 270 | 271 | - In DGraph it is allowed to skip fields in types that are already implemented in the interface. The GraphQl parser used for this project is very strict on the GraphQl specs and does not allow this, so you have to copy all fields you are using in the interface to your type. 272 | 273 | ## Examples 274 | 275 | Additional examples will be provided in the examples module 276 | -------------------------------------------------------------------------------- /api/errors.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | type HttpResponseStatus int 4 | 5 | type LambdaError struct { 6 | Underlying error 7 | Status HttpResponseStatus 8 | } 9 | 10 | func (l *LambdaError) Error() string { 11 | return l.Underlying.Error() 12 | } 13 | -------------------------------------------------------------------------------- /api/request.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | ) 7 | 8 | type AuthHeader struct { 9 | Key string `json:"key"` 10 | Value string `json:"value"` 11 | } 12 | 13 | type Directive struct { 14 | Name string `json:"name"` 15 | Arguments map[string]json.RawMessage `json:"arguments"` 16 | } 17 | 18 | type SelectionField struct { 19 | Alias string `json:"alias"` 20 | Name string `json:"name"` 21 | Arguments map[string]json.RawMessage `json:"arguments"` 22 | Directives []Directive `json:"directives"` 23 | SelectionSet []SelectionField `json:"slectionSet"` 24 | } 25 | 26 | type InfoField struct { 27 | Field SelectionField `json:"field"` 28 | } 29 | 30 | type Request struct { 31 | AccessToken string `json:"X-Dgraph-AccessToken"` 32 | Args map[string]json.RawMessage `json:"args"` 33 | Field InfoField `json:"info"` 34 | AuthHeader AuthHeader `json:"authHeader"` 35 | Resolver string `json:"resolver"` 36 | Parents json.RawMessage `json:"parents"` 37 | Event *Event `json:"event"` 38 | } 39 | 40 | type Event struct { 41 | TypeName string `json:"__typename"` 42 | CommitTs uint64 `json:"commitTs"` 43 | Operation string `json:"operation"` 44 | Add *AddEventInfo `json:"add"` 45 | Update *UpdateEventInfo `json:"update"` 46 | Delete *DeleteEventInfo `json:"delete"` 47 | } 48 | 49 | type AddEventInfo struct { 50 | RootUIDs []string `json:"rootUIDs"` 51 | Input []map[string]interface{} `json:"input"` 52 | } 53 | 54 | type UpdateEventInfo struct { 55 | RootUIDs []string `json:"rootUIDs"` 56 | SetPatch map[string]interface{} `json:"setPatch"` 57 | RemovePatch map[string]interface{} `json:"removePatch"` 58 | } 59 | 60 | type DeleteEventInfo struct { 61 | RootUIDs []string `json:"rootUIDs"` 62 | } 63 | 64 | type MiddlewareFunc func(MiddlewareContext) MiddlewareContext 65 | 66 | type MiddlewareContext struct { 67 | Ctx context.Context 68 | Request *Request 69 | } 70 | 71 | type HandlerFunc func(ctx context.Context, input []byte, parents []byte, authHeader AuthHeader) (interface{}, error) 72 | -------------------------------------------------------------------------------- /api/server.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "log" 8 | "net/http" 9 | "strings" 10 | "sync" 11 | 12 | "github.com/pkg/errors" 13 | 14 | "github.com/go-chi/chi" 15 | "github.com/go-chi/chi/middleware" 16 | ) 17 | 18 | type ExecuterInterface interface { 19 | Resolve(ctx context.Context, request *Request) ([]byte, *LambdaError) 20 | } 21 | 22 | type Lambda struct { 23 | Executor ExecuterInterface 24 | } 25 | 26 | func New(executer ExecuterInterface) *Lambda { 27 | return &Lambda{Executor: executer} 28 | } 29 | 30 | func (l *Lambda) Route(w http.ResponseWriter, r *http.Request) { 31 | res, err := l.resolve(w, r) 32 | if err != nil { 33 | fmt.Println(err.Error()) 34 | w.WriteHeader(int(err.Status)) 35 | w.Write([]byte(err.Error())) 36 | } 37 | w.Write(res) 38 | } 39 | 40 | func (l *Lambda) resolve(w http.ResponseWriter, r *http.Request) ([]byte, *LambdaError) { 41 | decoder := json.NewDecoder(r.Body) 42 | 43 | var request *Request 44 | err := decoder.Decode(&request) 45 | if err != nil { 46 | return nil, &LambdaError{Underlying: err, Status: http.StatusBadRequest} 47 | } 48 | if request == nil { 49 | return nil, &LambdaError{Underlying: errors.New("body cannot be nil"), Status: http.StatusBadRequest} 50 | } 51 | err = l.validate(request) 52 | if err != nil { 53 | return nil, &LambdaError{Underlying: errors.Wrap(err, "Invalid request"), Status: http.StatusBadRequest} 54 | } 55 | 56 | return l.Executor.Resolve(r.Context(), request) 57 | } 58 | 59 | func (l *Lambda) validate(request *Request) error { 60 | if request.Resolver == "" { 61 | return errors.New("Resolver or Event missing") 62 | } 63 | if strings.HasPrefix(request.Resolver, "Query.") || strings.HasPrefix(request.Resolver, "Mutation.") { 64 | if request.Args == nil { 65 | return errors.New("Missing arguments for query/mutation") 66 | } 67 | } else if request.Resolver == "$webhook" && request.Event == nil { 68 | return errors.New("Webhook must have event") 69 | } else if request.Resolver != "$webhook" && request.Parents == nil { 70 | return errors.New("Missing parents for field resolver") 71 | } 72 | return nil 73 | } 74 | 75 | func (l *Lambda) Serve(wg *sync.WaitGroup) (*http.Server, error) { 76 | r := chi.NewRouter() 77 | r.Use(middleware.Logger) 78 | r.Post("/graphql-worker", func(w http.ResponseWriter, r *http.Request) { 79 | res, err := l.resolve(w, r) 80 | if err != nil { 81 | fmt.Println(err.Error()) 82 | w.WriteHeader(int(err.Status)) 83 | w.Write([]byte(err.Error())) 84 | } 85 | w.Write(res) 86 | }) 87 | srv := &http.Server{ 88 | Addr: ":8686", 89 | Handler: r, 90 | } 91 | 92 | go func() { 93 | defer wg.Done() 94 | 95 | fmt.Println("Lambda listening on 8686") 96 | if err := srv.ListenAndServe(); err != http.ErrServerClosed { 97 | log.Fatalf("ListenAndServe(): %v", err) 98 | } 99 | }() 100 | 101 | return srv, nil 102 | } 103 | -------------------------------------------------------------------------------- /api/server_test.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "net/http" 8 | "net/http/httptest" 9 | "sync" 10 | "testing" 11 | "time" 12 | 13 | "github.com/stretchr/testify/assert" 14 | "github.com/stretchr/testify/mock" 15 | ) 16 | 17 | type ExecuterMock struct { 18 | mock.Mock 19 | } 20 | 21 | func (e ExecuterMock) Resolve(ctx context.Context, request *Request) ([]byte, *LambdaError) { 22 | e.Called(ctx, request) 23 | return nil, nil 24 | } 25 | 26 | var invalidRequests = []struct { 27 | body string 28 | expected int 29 | }{ 30 | {body: "", expected: http.StatusBadRequest}, 31 | {body: "[]", expected: http.StatusBadRequest}, 32 | {body: "invalid", expected: http.StatusBadRequest}, 33 | {body: "{", expected: http.StatusBadRequest}, 34 | {body: "{}", expected: http.StatusBadRequest}, 35 | {body: `{ "resolver":"" }`, expected: http.StatusBadRequest}, 36 | {body: `{ "resolver":"$webhook" }`, expected: http.StatusBadRequest}, 37 | {body: `{ "event": { "operation":""} }`, expected: http.StatusBadRequest}, 38 | {body: `{ "resolver":"", "event": { "operation":""} }`, expected: http.StatusBadRequest}, 39 | {body: `{ "resolver":"User.test" }`, expected: http.StatusBadRequest}, 40 | {body: `{ "resolver":"User.test", "event": { "operation":""} }`, expected: http.StatusBadRequest}, 41 | {body: `{ "resolver":"Query.test" }`, expected: http.StatusBadRequest}, 42 | {body: `{ "resolver":"Query.test", "parents": "" }`, expected: http.StatusBadRequest}, 43 | {body: `{ "resolver":"Query.test", "args": "" }`, expected: http.StatusBadRequest}, 44 | {body: `{ "resolver":"Mutation.test" }`, expected: http.StatusBadRequest}, 45 | {body: `{ "resolver":"Mutation.test", "parents": "" }`, expected: http.StatusBadRequest}, 46 | {body: `{ "resolver":"Mutation.test", "args": "" }`, expected: http.StatusBadRequest}, 47 | } 48 | 49 | var validRequests = []struct { 50 | body string 51 | expected int 52 | }{ 53 | {body: `{ "resolver":"User.test", "parents": "" }`, expected: http.StatusOK}, 54 | {body: `{ "resolver":"Query.test", "args": {} }`, expected: http.StatusOK}, 55 | {body: `{ "resolver":"Mutation.test", "args": {} }`, expected: http.StatusOK}, 56 | {body: `{ "resolver":"$webhook", "event": {} }`, expected: http.StatusOK}, 57 | } 58 | 59 | func Test_Route_Invalid_Body(t *testing.T) { 60 | em := &ExecuterMock{} 61 | lambda := New(em) 62 | 63 | for _, request := range invalidRequests { 64 | req := httptest.NewRequest(http.MethodPost, "/graphql-worker", bytes.NewBufferString(request.body)) 65 | w := httptest.NewRecorder() 66 | 67 | lambda.Route(w, req) 68 | 69 | assert.Equal(t, request.expected, w.Result().StatusCode) 70 | } 71 | } 72 | 73 | func Test_Route_Valid_Body(t *testing.T) { 74 | em := ExecuterMock{} 75 | em.On("Resolve", mock.Anything, mock.Anything).Return(nil, nil) 76 | 77 | lambda := New(em) 78 | 79 | for _, request := range validRequests { 80 | req := httptest.NewRequest(http.MethodPost, "/graphql-worker", bytes.NewBufferString(request.body)) 81 | w := httptest.NewRecorder() 82 | 83 | lambda.Route(w, req) 84 | 85 | assert.Equal(t, request.expected, w.Result().StatusCode) 86 | em.AssertExpectations(t) 87 | } 88 | } 89 | 90 | func Test_Serve_Invalid_Body(t *testing.T) { 91 | httpServerExitDone := &sync.WaitGroup{} 92 | httpServerExitDone.Add(1) 93 | 94 | em := &ExecuterMock{} 95 | lambda := New(em) 96 | 97 | srv, err := lambda.Serve(httpServerExitDone) 98 | assert.NoError(t, err) 99 | 100 | for _, request := range invalidRequests { 101 | res, err := http.Post("http://localhost:8686/graphql-worker", "application/json", bytes.NewBufferString(request.body)) 102 | assert.NoError(t, err) 103 | assert.Equal(t, request.expected, res.StatusCode) 104 | time.Sleep(1 * time.Second) 105 | } 106 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 107 | defer cancel() 108 | 109 | if err := srv.Shutdown(ctx); err != nil { 110 | assert.NoError(t, err) 111 | } 112 | httpServerExitDone.Wait() 113 | } 114 | 115 | func Test_Serve_Valid_Body(t *testing.T) { 116 | httpServerExitDone := &sync.WaitGroup{} 117 | httpServerExitDone.Add(1) 118 | 119 | em := &ExecuterMock{} 120 | em.On("Resolve", mock.Anything, mock.Anything).Return(nil, nil) 121 | lambda := New(em) 122 | 123 | srv, err := lambda.Serve(httpServerExitDone) 124 | assert.NoError(t, err) 125 | 126 | for _, request := range validRequests { 127 | res, err := http.Post("http://localhost:8686/graphql-worker", "application/json", bytes.NewBufferString(request.body)) 128 | fmt.Println(res.Status) 129 | assert.NoError(t, err) 130 | assert.Equal(t, request.expected, res.StatusCode) 131 | em.AssertExpectations(t) 132 | time.Sleep(1 * time.Second) 133 | } 134 | if err := srv.Shutdown(context.TODO()); err != nil { 135 | assert.NoError(t, err) 136 | } 137 | httpServerExitDone.Wait() 138 | } 139 | -------------------------------------------------------------------------------- /cmd/example.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/schartey/dgraph-lambda-go/examples" 5 | "github.com/urfave/cli/v2" 6 | ) 7 | 8 | var exampleCmd = &cli.Command{ 9 | Name: "example", 10 | Usage: "example", 11 | Description: "Runs example server", 12 | Action: func(ctx *cli.Context) error { 13 | examples.RunWithServer() 14 | return nil 15 | }, 16 | } 17 | -------------------------------------------------------------------------------- /cmd/generate.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/schartey/dgraph-lambda-go/codegen/config" 5 | "github.com/schartey/dgraph-lambda-go/codegen/generator" 6 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 7 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 8 | "github.com/schartey/dgraph-lambda-go/internal" 9 | "github.com/urfave/cli/v2" 10 | ) 11 | 12 | var generateCmd = &cli.Command{ 13 | Name: "generate", 14 | Usage: "generate -c \"lambda.yaml\"", 15 | Description: "generates types, resolvers and middleware from schema in lambda.yaml", 16 | Flags: []cli.Flag{ 17 | &cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "the lambda config file"}, 18 | }, 19 | Action: func(ctx *cli.Context) error { 20 | configFile := ctx.String("config") 21 | 22 | if configFile == "" { 23 | configFile = "lambda.yaml" 24 | } 25 | 26 | moduleName, err := internal.GetModuleName() 27 | if err != nil { 28 | return err 29 | } 30 | 31 | config, err := config.LoadConfigFile(moduleName, configFile) 32 | if err != nil { 33 | return err 34 | } 35 | err = config.LoadConfig(configFile) 36 | if err != nil { 37 | return err 38 | } 39 | 40 | if err := config.LoadSchema(); err != nil { 41 | return err 42 | } 43 | 44 | parser := parser.NewParser(config.Schema, config.Packages, config.Force) 45 | parsedTree, err := parser.Parse() 46 | if err != nil { 47 | return err 48 | } 49 | 50 | if err := config.Bind(parsedTree); err != nil { 51 | return err 52 | } 53 | 54 | rewriter := rewriter.New(config, parsedTree) 55 | 56 | if err := rewriter.Load(); err != nil { 57 | return err 58 | } 59 | 60 | if err := generator.Generate(config, parsedTree, rewriter); err != nil { 61 | return err 62 | } 63 | 64 | // Run go mod tidy 65 | if err := internal.FixImports(); err != nil { 66 | return err 67 | } 68 | 69 | return nil 70 | }, 71 | } 72 | -------------------------------------------------------------------------------- /cmd/init.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/schartey/dgraph-lambda-go/codegen/config" 5 | "github.com/schartey/dgraph-lambda-go/codegen/generator" 6 | "github.com/schartey/dgraph-lambda-go/internal" 7 | "github.com/urfave/cli/v2" 8 | ) 9 | 10 | var initCmd = &cli.Command{ 11 | Name: "init", 12 | Usage: "init -c \"lambda.yaml\"", 13 | Description: "generates folder structure and lambda-server. Call generate command afterwards", 14 | Flags: []cli.Flag{ 15 | &cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "the lambda config file"}, 16 | }, 17 | Action: func(ctx *cli.Context) error { 18 | configFile := ctx.String("config") 19 | 20 | if configFile == "" { 21 | configFile = "lambda.yaml" 22 | } 23 | 24 | moduleName, err := internal.GetModuleName() 25 | if err != nil { 26 | return err 27 | } 28 | 29 | if err := generator.GenerateConfig(configFile); err != nil { 30 | return err 31 | } 32 | 33 | config, err := config.LoadConfigFile(moduleName, configFile) 34 | if err != nil { 35 | return err 36 | } 37 | 38 | config.LoadSchema() 39 | if err != nil { 40 | return err 41 | } 42 | 43 | return generator.Init(config) 44 | }, 45 | } 46 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | 9 | "github.com/urfave/cli/v2" 10 | ) 11 | 12 | // TODO: Add model generation from graphql introspection 13 | func Execute() { 14 | app := cli.NewApp() 15 | app.Name = "dgraph-lambda-go" 16 | app.Usage = initCmd.Usage 17 | app.Description = "This project implements the dgraph-lambda server based on go." 18 | app.HideVersion = true 19 | app.Flags = initCmd.Flags 20 | app.Version = "0.5.0" 21 | app.Before = func(context *cli.Context) error { 22 | if context.Bool("verbose") { 23 | log.SetFlags(0) 24 | } else { 25 | log.SetOutput(ioutil.Discard) 26 | } 27 | return nil 28 | } 29 | 30 | app.Action = initCmd.Action 31 | app.Commands = []*cli.Command{ 32 | initCmd, 33 | generateCmd, 34 | exampleCmd, 35 | } 36 | 37 | if err := app.Run(os.Args); err != nil { 38 | fmt.Fprint(os.Stderr, err.Error()) 39 | os.Exit(1) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /codegen/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "go/types" 6 | "io/ioutil" 7 | "path" 8 | "path/filepath" 9 | "regexp" 10 | "strings" 11 | 12 | "github.com/pkg/errors" 13 | "github.com/schartey/dgraph-lambda-go/codegen/graphql" 14 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 15 | "github.com/schartey/dgraph-lambda-go/internal" 16 | "github.com/vektah/gqlparser/v2" 17 | "github.com/vektah/gqlparser/v2/ast" 18 | "golang.org/x/tools/go/packages" 19 | "gopkg.in/yaml.v2" 20 | ) 21 | 22 | var resolverTemplateRegex = regexp.MustCompile(`\{([^)]+)\}.resolver.*`) 23 | 24 | type PackageConfig struct { 25 | Filename string 26 | Package string 27 | } 28 | 29 | type ResolverConfig struct { 30 | Layout string `yaml:"layout"` 31 | Dir string `yaml:"dir"` 32 | Package string `yaml:"package"` 33 | FilenameTemplate string `yaml:"filename_template"` 34 | } 35 | 36 | type Config struct { 37 | SchemaFilename []string `yaml:"schema"` 38 | Exec PackageConfig `yaml:"exec"` 39 | Model PackageConfig `yaml:"model"` 40 | Resolver ResolverConfig `yaml:"resolver"` 41 | Force []string `yaml:"force"` 42 | AutoBind []string `yaml:"autobind"` 43 | Server struct { 44 | Standalone bool `yaml:"standalone"` 45 | } `yaml:"server"` 46 | 47 | Sources []*ast.Source `yaml:"-"` 48 | Packages *internal.Packages `yaml:"-"` 49 | Schema *ast.Schema `yaml:"-"` 50 | Root string `yaml:"-"` 51 | DefaultModelPackage *packages.Package `yaml:"-"` 52 | ResolverFilename string `yaml:"-"` 53 | } 54 | 55 | func LoadConfigFile(moduleName string, filename string) (*Config, error) { 56 | config := &Config{} 57 | 58 | b, err := ioutil.ReadFile(filename) 59 | if err != nil { 60 | return nil, errors.Wrap(err, "unable to read config") 61 | } 62 | 63 | if err := yaml.UnmarshalStrict(b, config); err != nil { 64 | return nil, errors.Wrap(err, "unable to parse config") 65 | } 66 | 67 | if config.Exec.Package == "" || config.Model.Package == "" || config.Resolver.Package == "" { 68 | return nil, errors.New("package name must be set in lambda config") 69 | } 70 | 71 | if config.Exec.Filename == "" || config.Model.Filename == "" { 72 | return nil, errors.New("file names for generated executer and model must be set in lambda config") 73 | } 74 | 75 | if config.Resolver.Dir == "" { 76 | return nil, errors.New("resovler target direcotry must be set in lambda config") 77 | } 78 | 79 | config.Root = moduleName 80 | 81 | resolverTemplateSub := resolverTemplateRegex.FindStringSubmatch(config.Resolver.FilenameTemplate) 82 | if len(resolverTemplateSub) > 1 { 83 | if resolverTemplateSub[1] != "resolver" { 84 | return nil, errors.New("Currently only {resolver}.resolver.go is supported as resolver filename template") 85 | } else { 86 | config.ResolverFilename = resolverTemplateSub[1] 87 | } 88 | } else { 89 | return nil, errors.New("Could not find match name for filename template") 90 | } 91 | 92 | return config, nil 93 | } 94 | 95 | func (config *Config) LoadConfig(filename string) error { 96 | preGlobbing := config.SchemaFilename 97 | 98 | abs, err := filepath.Abs(filename) 99 | if err != nil { 100 | return errors.Wrap(err, "unable to detect config folder") 101 | } 102 | abs = filepath.Dir(abs) 103 | 104 | var schemaFiles []string 105 | for _, f := range preGlobbing { 106 | var matches []string 107 | 108 | fp := filepath.Join(abs, f) 109 | 110 | matches, err = filepath.Glob(fp) 111 | if err != nil { 112 | return errors.Wrapf(err, "failed to glob schema filename %s", f) 113 | } 114 | 115 | for _, m := range matches { 116 | exists := false 117 | for _, s := range schemaFiles { 118 | if s == m { 119 | exists = true 120 | break 121 | } 122 | } 123 | if !exists { 124 | schemaFiles = append(schemaFiles, m) 125 | } 126 | } 127 | } 128 | config.SchemaFilename = schemaFiles 129 | 130 | for _, filename := range config.SchemaFilename { 131 | filename = filepath.ToSlash(filename) 132 | var err error 133 | var schemaRaw []byte 134 | schemaRaw, err = ioutil.ReadFile(filename) 135 | if err != nil { 136 | errors.Wrap(err, "unable to open schema") 137 | } 138 | 139 | config.Sources = append(config.Sources, &ast.Source{Input: graphql.SchemaInputs + graphql.DirectiveDefs}) 140 | config.Sources = append(config.Sources, &ast.Source{Input: graphql.ApolloSchemaQueries + graphql.ApolloSchemaExtras}) 141 | config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) 142 | } 143 | 144 | if config.Packages == nil { 145 | config.Packages = &internal.Packages{} 146 | 147 | defaultModelPath := config.Root + "/" + path.Dir(config.Model.Filename) 148 | 149 | defaultPackage, err := config.Packages.Load(defaultModelPath) 150 | if err != nil { 151 | return errors.Wrap(err, "Could not load generated model package") 152 | } 153 | config.DefaultModelPackage = defaultPackage 154 | } 155 | 156 | return nil 157 | } 158 | 159 | func (c *Config) LoadSchema() error { 160 | if c.Schema == nil { 161 | if err := c.loadSchema(); err != nil { 162 | return errors.Wrap(err, "Could not load schema") 163 | } 164 | } 165 | return nil 166 | } 167 | 168 | func (c *Config) loadSchema() error { 169 | schema, err := gqlparser.LoadSchema(c.Sources...) 170 | if err != nil { 171 | return err 172 | } 173 | 174 | if schema.Query == nil { 175 | schema.Query = &ast.Definition{ 176 | Kind: ast.Object, 177 | Name: "Query", 178 | } 179 | schema.Types["Query"] = schema.Query 180 | } 181 | 182 | c.Schema = schema 183 | return nil 184 | } 185 | 186 | func (c *Config) Bind(parsedTree *parser.Tree) error { 187 | 188 | if len(c.AutoBind) == 0 { 189 | for _, it := range parsedTree.ModelTree.Models { 190 | c.bindPackage(nil, it.GoType, it.Name) 191 | } 192 | 193 | for _, it := range parsedTree.ModelTree.Interfaces { 194 | c.bindPackage(nil, it.GoType, it.Name) 195 | } 196 | 197 | for _, it := range parsedTree.ModelTree.Enums { 198 | c.bindPackage(nil, it.GoType, it.Name) 199 | } 200 | 201 | for _, it := range parsedTree.ModelTree.Scalars { 202 | c.bindPackage(nil, it.GoType, it.Name) 203 | } 204 | } 205 | 206 | for _, autobind := range c.AutoBind { 207 | var pkg *packages.Package 208 | pkg, err := c.Packages.PackageFromPath(autobind) 209 | if err != nil { 210 | pkg, err = c.Packages.Load(autobind) 211 | if err != nil { 212 | return errors.Wrap(err, "Could not load package") 213 | } 214 | } 215 | 216 | for _, it := range parsedTree.ModelTree.Models { 217 | if it.GoType.TypeName.Exported() { 218 | if it.GoType.TypeName.Pkg() == nil { 219 | c.bindPackage(pkg, it.GoType, it.Name) 220 | } 221 | } 222 | } 223 | 224 | for _, it := range parsedTree.ModelTree.Interfaces { 225 | if it.GoType.TypeName.Exported() { 226 | if it.GoType.TypeName.Pkg() == nil { 227 | c.bindPackage(pkg, it.GoType, it.Name) 228 | } 229 | } 230 | } 231 | 232 | for _, it := range parsedTree.ModelTree.Enums { 233 | if it.GoType.TypeName.Exported() { 234 | if it.GoType.TypeName.Pkg() == nil { 235 | c.bindPackage(pkg, it.GoType, it.Name) 236 | } 237 | } 238 | } 239 | 240 | for _, it := range parsedTree.ModelTree.Scalars { 241 | if it.GoType.TypeName.Exported() { 242 | if it.GoType.TypeName.Pkg() == nil { 243 | c.bindPackage(pkg, it.GoType, it.Name) 244 | } 245 | } 246 | } 247 | } 248 | 249 | return nil 250 | } 251 | 252 | func (c *Config) pkgHasType(pkg *packages.Package, name string) bool { 253 | for _, typeName := range pkg.Types.Scope().Names() { 254 | if name == typeName { 255 | return true 256 | } 257 | } 258 | return false 259 | } 260 | 261 | func (c *Config) isCustomInDefaultPkg(pkg *packages.Package, name string) bool { 262 | if fileName, err := c.Packages.GetFileNameType(pkg.PkgPath, name); err == nil && !strings.Contains(fileName, c.Model.Filename) { 263 | return true 264 | } 265 | return false 266 | } 267 | 268 | func (c *Config) bindPackage(pkg *packages.Package, t *parser.GoType, name string) { 269 | if t.TypeName.Exported() { 270 | if c.isCustomInDefaultPkg(c.DefaultModelPackage, name) { 271 | t.TypeName = types.NewTypeName(0, types.NewPackage(c.DefaultModelPackage.PkgPath, c.DefaultModelPackage.Name), name, nil) 272 | t.Autobind = true 273 | } else if pkg != nil && pkg.PkgPath != c.DefaultModelPackage.PkgPath && c.pkgHasType(pkg, name) { 274 | t.TypeName = types.NewTypeName(0, types.NewPackage(pkg.PkgPath, pkg.Name), name, nil) 275 | t.Autobind = true 276 | fmt.Printf("Autobind: %s -> %s\n", name, t.TypeName.Pkg().Name()) 277 | } else { 278 | t.TypeName = types.NewTypeName(0, types.NewPackage(c.DefaultModelPackage.PkgPath, c.DefaultModelPackage.Name), name, nil) 279 | } 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /codegen/config/config_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "path/filepath" 7 | "testing" 8 | 9 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 10 | "github.com/schartey/dgraph-lambda-go/internal" 11 | "github.com/stretchr/testify/assert" 12 | ) 13 | 14 | var autobindValues = []string{"github.com/schartey/dgraph-lambda-go/examples/models"} 15 | var models = []string{"User", "Author", "Apple", "Figure", "Hotel"} 16 | var fieldResolvers = []string{"User.reputation", "User.rank", "User.active", "Post.additionalInfo", "Figure.size"} 17 | 18 | var queryResolvers = []string{"getApples", "getTopAuthors", "getHotelByName"} 19 | 20 | var mutationResolvers = []string{"newAuthor"} 21 | 22 | var middlewareResolvers = []string{"user", "admin"} 23 | 24 | func Test_LoadConfig(t *testing.T) { 25 | config, err := LoadConfigFile("github.com/schartey/dgraph-lambda-go", "../../lambda.yaml") 26 | assert.NoError(t, err) 27 | err = config.LoadConfig("../../lambda.yaml") 28 | assert.NoError(t, err) 29 | 30 | assert.Contains(t, filepath.ToSlash(config.SchemaFilename[0]), path.Join("dgraph-lambda-go", "examples", "test.graphql")) 31 | assert.Equal(t, "examples/lambda/generated/generated.go", config.Exec.Filename) 32 | assert.Equal(t, "generated", config.Exec.Package) 33 | assert.Equal(t, "examples/lambda/model/models_gen.go", config.Model.Filename) 34 | assert.Equal(t, "model", config.Model.Package) 35 | assert.Equal(t, "github.com/schartey/dgraph-lambda-go/examples/models", config.AutoBind[0]) 36 | assert.Equal(t, "follow-schema", config.Resolver.Layout) 37 | assert.Equal(t, "examples/lambda/resolvers", config.Resolver.Dir) 38 | assert.Equal(t, "resolvers", config.Resolver.Package) 39 | assert.Equal(t, "{resolver}.resolver.go", config.Resolver.FilenameTemplate) 40 | assert.Equal(t, true, config.Server.Standalone) 41 | assert.Equal(t, "github.com/schartey/dgraph-lambda-go", config.Root) 42 | assert.NotNil(t, config.DefaultModelPackage) 43 | assert.Equal(t, "model", config.DefaultModelPackage.Name) 44 | assert.Equal(t, "github.com/schartey/dgraph-lambda-go/examples/lambda/model", config.DefaultModelPackage.PkgPath) 45 | assert.Equal(t, 3, len(config.Sources)) 46 | assert.Contains(t, config.Sources[2].Name, "dgraph-lambda-go/examples/test.graphql") 47 | } 48 | 49 | func Test_LoadConfig_Fail(t *testing.T) { 50 | // Non existent file 51 | _, err := LoadConfigFile("github.com/schartey/dgraph-lambda-go", "./lambda.yaml") 52 | assert.Error(t, err) 53 | 54 | // Invalid file type 55 | _, err = LoadConfigFile("github.com/schartey/dgraph-lambda-go", "./config.go") 56 | assert.Error(t, err) 57 | 58 | for i := 1; i < 6; i++ { 59 | // Invalid file type 60 | _, err = LoadConfigFile("github.com/schartey/dgraph-lambda-go", fmt.Sprintf("../../test_resources/faulty%d.yaml", i)) 61 | assert.Error(t, err) 62 | } 63 | } 64 | 65 | func Test_loadSchema(t *testing.T) { 66 | config, err := LoadConfigFile("github.com/schartey/dgraph-lambda-go", "../../lambda.yaml") 67 | assert.NoError(t, err) 68 | err = config.LoadConfig("../../lambda.yaml") 69 | assert.NoError(t, err) 70 | 71 | err = config.loadSchema() 72 | assert.NoError(t, err) 73 | assert.NotNil(t, config.Schema) 74 | } 75 | 76 | func Test_Config(t *testing.T) { 77 | moduleName, err := internal.GetModuleName() 78 | if err != nil { 79 | t.FailNow() 80 | } 81 | 82 | config, err := LoadConfigFile(moduleName, "../../lambda.yaml") 83 | if err != nil { 84 | fmt.Println(err.Error()) 85 | t.FailNow() 86 | } 87 | err = config.LoadConfig("../../lambda.yaml") 88 | if err != nil { 89 | t.FailNow() 90 | } 91 | 92 | for _, value := range autobindValues { 93 | if !contains(value, config.AutoBind) { 94 | fmt.Println("Autobind Value missing: " + value) 95 | t.FailNow() 96 | } 97 | } 98 | // Check all values parsed from lambda.yaml 99 | 100 | if err := config.LoadSchema(); err != nil { 101 | fmt.Println(err.Error()) 102 | t.FailNow() 103 | } 104 | 105 | /* for _, m := range models { 106 | if !containsModel(m, config.ParsedTree.ModelTree.Models) { 107 | fmt.Println("Missing model after parsing: " + m) 108 | t.FailNow() 109 | } 110 | } 111 | 112 | for _, f := range fieldResolvers { 113 | if !containsFieldResolver(f, config.ParsedTree.ResolverTree.FieldResolvers) { 114 | fmt.Println("Missing field-resolver after parsing: " + f) 115 | t.FailNow() 116 | } 117 | } 118 | 119 | for _, q := range queryResolvers { 120 | if !containsQueryResolver(q, config.ParsedTree.ResolverTree.Queries) { 121 | fmt.Println("Missing query-resolver after parsing: " + q) 122 | t.FailNow() 123 | } 124 | } 125 | 126 | for _, m := range mutationResolvers { 127 | if !containsMutationResolver(m, config.ParsedTree.ResolverTree.Mutations) { 128 | fmt.Println("Missing mutation-resolver after parsing: " + m) 129 | t.FailNow() 130 | } 131 | } 132 | 133 | for _, m := range middlewareResolvers { 134 | if !containsMiddlewareResolver(m, config.ParsedTree.Middleware) { 135 | fmt.Println("Missing middleware resolver: " + m) 136 | t.FailNow() 137 | } 138 | }*/ 139 | } 140 | 141 | func contains(s string, arr []string) bool { 142 | for _, v := range arr { 143 | if s == v { 144 | return true 145 | } 146 | } 147 | return false 148 | } 149 | 150 | func containsModel(modelName string, models map[string]*parser.Model) bool { 151 | for _, model := range models { 152 | if model.Name == modelName { 153 | return true 154 | } 155 | } 156 | return false 157 | } 158 | 159 | func containsFieldResolver(fieldResolverName string, fieldResolvers map[string]*parser.FieldResolver) bool { 160 | for _, fieldResolver := range fieldResolvers { 161 | if fmt.Sprintf("%s.%s", fieldResolver.Parent.Name, fieldResolver.Field.Name) == fieldResolverName { 162 | return true 163 | } 164 | } 165 | return false 166 | } 167 | 168 | func containsQueryResolver(queryResolverName string, queries map[string]*parser.Query) bool { 169 | for _, query := range queries { 170 | if query.Name == queryResolverName { 171 | return true 172 | } 173 | } 174 | return false 175 | } 176 | 177 | func containsMutationResolver(mutationResolverName string, mutations map[string]*parser.Mutation) bool { 178 | for _, mutation := range mutations { 179 | if mutation.Name == mutationResolverName { 180 | return true 181 | } 182 | } 183 | return false 184 | } 185 | 186 | func containsMiddlewareResolver(middlewareResolverName string, middleware map[string]string) bool { 187 | for _, m := range middleware { 188 | if m == middlewareResolverName { 189 | return true 190 | } 191 | } 192 | return false 193 | } 194 | -------------------------------------------------------------------------------- /codegen/generator/executer_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "go/types" 5 | "os" 6 | "path" 7 | "text/template" 8 | 9 | "github.com/schartey/dgraph-lambda-go/codegen/config" 10 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 11 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 12 | ) 13 | 14 | func generateExecuter(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 15 | f, err := os.Create(c.Exec.Filename) 16 | if err != nil { 17 | return err 18 | } 19 | defer f.Close() 20 | 21 | pkgs := make(map[string]*types.Package) 22 | var lambdaOnMutate []string 23 | 24 | for _, m := range parsedTree.ModelTree.Models { 25 | if len(m.LambdaOnMutate) > 0 { 26 | lambdaOnMutate = append(lambdaOnMutate, m.Name) 27 | } 28 | } 29 | 30 | for _, m := range parsedTree.ResolverTree.FieldResolvers { 31 | if m.Field.TypeName.Exported() { 32 | pkgs[m.Field.TypeName.Pkg().Name()] = m.Field.TypeName.Pkg() 33 | } 34 | if m.Parent.TypeName.Exported() { 35 | pkgs[m.Parent.TypeName.Pkg().Name()] = m.Parent.TypeName.Pkg() 36 | } 37 | } 38 | 39 | for _, m := range parsedTree.ResolverTree.Queries { 40 | if m.Return.TypeName.Exported() { 41 | //pkgs[m.Return.TypeName.Pkg().Name()] = m.Return.TypeName.Pkg() 42 | } 43 | 44 | for _, f := range m.Arguments { 45 | if f.TypeName.Exported() { 46 | pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg() 47 | } 48 | } 49 | } 50 | 51 | for _, m := range parsedTree.ResolverTree.Mutations { 52 | if m.Return.TypeName.Exported() { 53 | pkgs[m.Return.TypeName.Pkg().Name()] = m.Return.TypeName.Pkg() 54 | } 55 | 56 | for _, f := range m.Arguments { 57 | if f.TypeName.Exported() { 58 | pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg() 59 | } 60 | } 61 | } 62 | 63 | pkgs["context"] = types.NewPackage("context", "context") 64 | pkgs["errors"] = types.NewPackage("errors", "errors") 65 | pkgs["http"] = types.NewPackage("net/http", "http") 66 | pkgs["strings"] = types.NewPackage("strings", "strings") 67 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 68 | 69 | if len(parsedTree.ResolverTree.FieldResolvers) > 0 || 70 | len(parsedTree.ResolverTree.Queries) > 0 || 71 | len(parsedTree.ResolverTree.Mutations) > 0 { 72 | pkgs["json"] = types.NewPackage("encoding/json", "json") 73 | } 74 | 75 | pkgs[c.Resolver.Package] = types.NewPackage(path.Join(c.Root, c.Resolver.Dir), c.Resolver.Package) 76 | 77 | err = executerTemplate.Execute(f, struct { 78 | FieldResolvers map[string]*parser.FieldResolver 79 | Queries map[string]*parser.Query 80 | Mutations map[string]*parser.Mutation 81 | Middleware map[string]string 82 | Models map[string]*parser.Model 83 | LambdaOnMutate []string 84 | Packages map[string]*types.Package 85 | PackageName string 86 | ResolverPackageName string 87 | }{ 88 | FieldResolvers: parsedTree.ResolverTree.FieldResolvers, 89 | Queries: parsedTree.ResolverTree.Queries, 90 | Mutations: parsedTree.ResolverTree.Mutations, 91 | Middleware: parsedTree.Middleware, 92 | Models: parsedTree.ModelTree.Models, 93 | LambdaOnMutate: lambdaOnMutate, 94 | Packages: pkgs, 95 | PackageName: c.Exec.Package, 96 | ResolverPackageName: c.Resolver.Package, 97 | }) 98 | if err != nil { 99 | return err 100 | } 101 | return nil 102 | } 103 | 104 | var executerTemplate = template.Must(template.New("executer").Funcs(template.FuncMap{ 105 | "path": pkgPath, 106 | "typeName": typeName, 107 | "ref": resolverRef, 108 | "untitle": untitle, 109 | "args": args, 110 | "pointer": pointer, 111 | }).Parse(` 112 | package {{.PackageName}} 113 | 114 | import( 115 | {{- range $pkg := .Packages }} 116 | "{{ $pkg | path }}"{{- end}} 117 | ) 118 | 119 | type Executer struct { 120 | api.ExecuterInterface 121 | fieldResolver {{.ResolverPackageName}}.FieldResolver 122 | queryResolver {{.ResolverPackageName}}.QueryResolver 123 | mutationResolver {{.ResolverPackageName}}.MutationResolver 124 | middlewareResolver {{.ResolverPackageName}}.MiddlewareResolver 125 | webhookResolver {{.ResolverPackageName}}.WebhookResolver 126 | } 127 | 128 | func NewExecuter(resolver *{{.ResolverPackageName}}.Resolver) api.ExecuterInterface { 129 | return Executer{fieldResolver: {{.ResolverPackageName}}.FieldResolver{Resolver: resolver}, queryResolver: {{.ResolverPackageName}}.QueryResolver{Resolver: resolver}, mutationResolver: {{.ResolverPackageName}}.MutationResolver{Resolver: resolver}, middlewareResolver: {{.ResolverPackageName}}.MiddlewareResolver{Resolver: resolver}, webhookResolver: {{.ResolverPackageName}}.WebhookResolver{Resolver: resolver}} 130 | } 131 | 132 | func (e Executer) Resolve(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 133 | if request.Resolver == "$webhook" { 134 | return nil, e.resolveWebhook(ctx, request) 135 | } else { 136 | parentsBytes, underlyingError := request.Parents.MarshalJSON() 137 | if underlyingError != nil { 138 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 139 | } 140 | 141 | mc := &api.MiddlewareContext{Ctx: ctx, Request: request} 142 | if err = e.middleware(mc); err != nil { 143 | return nil, err 144 | } 145 | ctx = mc.Ctx 146 | request = mc.Request 147 | 148 | if strings.HasPrefix(request.Resolver, "Query.") { 149 | return e.resolveQuery(ctx, request) 150 | } else if strings.HasPrefix(request.Resolver, "Mutation.") { 151 | return e.resolveMutation(ctx, request) 152 | } else { 153 | return e.resolveField(ctx, request, parentsBytes) 154 | } 155 | } 156 | } 157 | 158 | func (e Executer) middleware(mc *api.MiddlewareContext) (err *api.LambdaError) { 159 | switch mc.Request.Resolver { 160 | {{- range $fieldResolver := .FieldResolvers}}{{ if ne (len $fieldResolver.Middleware) 0 }} 161 | case "{{$fieldResolver.Parent.Name }}.{{$fieldResolver.Field.Name}}": 162 | { 163 | {{- range $middleware := $fieldResolver.Middleware}} 164 | if err = e.middlewareResolver.Middleware_{{$middleware}}(mc); err != nil { 165 | return err 166 | } 167 | {{- end}} 168 | break 169 | } 170 | {{ end }}{{- end }} 171 | 172 | {{- range $query := .Queries}}{{ if ne (len $query.Middleware) 0 }} 173 | case "Query.{{$query.Name}}": 174 | { 175 | {{- range $middleware := $query.Middleware}} 176 | if err = e.middlewareResolver.Middleware_{{$middleware}}(mc); err != nil { 177 | return err 178 | } 179 | {{- end}} 180 | break 181 | } 182 | {{ end }}{{- end }} 183 | {{- range $mutation := .Mutations}}{{ if ne (len $mutation.Middleware) 0 }} 184 | case "Mutation.{{$mutation.Name}}": 185 | { 186 | {{- range $middleware := $mutation.Middleware}} 187 | if err = e.middlewareResolver.Middleware_{{$middleware}}(mc); err != nil { 188 | return err 189 | } 190 | {{- end}} 191 | break 192 | } 193 | {{ end }}{{- end }} 194 | } 195 | return nil 196 | } 197 | 198 | func (e Executer) resolveField(ctx context.Context, request *api.Request, parentsBytes []byte) (response []byte, err *api.LambdaError) { 199 | switch request.Resolver { 200 | {{- range $fieldResolver := .FieldResolvers}} 201 | case "{{$fieldResolver.Parent.Name }}.{{$fieldResolver.Field.Name}}": 202 | { 203 | var parents []{{ pointer $fieldResolver.Parent.GoType false }} 204 | json.Unmarshal(parentsBytes, &parents) 205 | 206 | result, err := e.fieldResolver.{{$fieldResolver.Parent.Name }}_{{$fieldResolver.Field.Name}}(ctx, parents, request.AuthHeader) 207 | if err != nil { 208 | return nil, err 209 | } 210 | 211 | var underlyingError error 212 | response, underlyingError = json.Marshal(result) 213 | if underlyingError != nil { 214 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 215 | } else { 216 | return response, nil 217 | } 218 | break 219 | } 220 | {{- end }} 221 | } 222 | 223 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 224 | } 225 | 226 | func (e Executer) resolveQuery(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 227 | switch request.Resolver { 228 | {{- range $query := .Queries}} 229 | case "Query.{{$query.Name}}": 230 | { 231 | {{- range $arg := $query.Arguments }} 232 | var {{ $arg.Name }} {{ pointer $arg.GoType $arg.IsArray }} 233 | json.Unmarshal(request.Args["{{$arg.Name}}"], &{{$arg.Name}}) 234 | {{- end }} 235 | result, err := e.queryResolver.Query_{{$query.Name}}(ctx{{ if ne (len $query.Arguments) 0}}, {{$query.Arguments | args}}{{end}}, request.AuthHeader) 236 | if err != nil { 237 | return nil, err 238 | } 239 | 240 | var underlyingError error 241 | response, underlyingError = json.Marshal(result) 242 | if underlyingError != nil { 243 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 244 | } else { 245 | return response, nil 246 | } 247 | break 248 | } 249 | {{- end }} 250 | } 251 | 252 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 253 | } 254 | 255 | func (e Executer) resolveMutation(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 256 | switch request.Resolver { 257 | {{- range $mutation := .Mutations}} 258 | case "Mutation.{{$mutation.Name}}": 259 | { 260 | {{- range $arg := $mutation.Arguments }} 261 | var {{ $arg.Name }} {{ pointer $arg.GoType $arg.IsArray }} 262 | json.Unmarshal(request.Args["{{$arg.Name}}"], &{{$arg.Name}}) 263 | {{- end }} 264 | result, err := e.mutationResolver.Mutation_{{$mutation.Name}}(ctx{{ if ne (len $mutation.Arguments) 0}}, {{$mutation.Arguments | args}}{{ end }}, request.AuthHeader) 265 | if err != nil { 266 | return nil, err 267 | } 268 | 269 | var underlyingError error 270 | response, underlyingError = json.Marshal(result) 271 | if underlyingError != nil { 272 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 273 | } else { 274 | return response, nil 275 | } 276 | break 277 | } 278 | {{- end }} 279 | } 280 | 281 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 282 | } 283 | 284 | func (e Executer) resolveWebhook(ctx context.Context, request *api.Request) (err *api.LambdaError) { 285 | switch request.Event.TypeName { 286 | {{- range $name := .LambdaOnMutate}} 287 | case "{{$name}}": 288 | err = e.webhookResolver.Webhook_{{$name}}(ctx, request.Event) 289 | return err 290 | {{- end }} 291 | } 292 | 293 | return &api.LambdaError{Underlying: errors.New("could not find webhook resolver"), Status: http.StatusNotFound} 294 | } 295 | 296 | `)) 297 | -------------------------------------------------------------------------------- /codegen/generator/field_resolver_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "errors" 5 | "go/types" 6 | "os" 7 | "path" 8 | "text/template" 9 | 10 | "github.com/schartey/dgraph-lambda-go/codegen/config" 11 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 12 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 13 | ) 14 | 15 | func generateFieldResolvers(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 16 | 17 | if c.ResolverFilename == "resolver" { 18 | 19 | fileName := path.Join(c.Resolver.Dir, "field.resolver.go") 20 | f, err := os.Create(fileName) 21 | if err != nil { 22 | return err 23 | } 24 | defer f.Close() 25 | 26 | var pkgs = make(map[string]*types.Package) 27 | 28 | for _, m := range parsedTree.ResolverTree.FieldResolvers { 29 | if m.Field.TypeName.Exported() { 30 | pkgs[m.Field.TypeName.Pkg().Name()] = m.Field.TypeName.Pkg() 31 | } 32 | if m.Parent.TypeName.Exported() { 33 | pkgs[m.Parent.TypeName.Pkg().Name()] = m.Parent.TypeName.Pkg() 34 | } 35 | } 36 | if len(parsedTree.ResolverTree.FieldResolvers) > 0 { 37 | pkgs["context"] = types.NewPackage("context", "context") 38 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 39 | } 40 | 41 | err = fieldResolverTemplate.Execute(f, struct { 42 | FieldResolvers map[string]*parser.FieldResolver 43 | Rewriter *rewriter.Rewriter 44 | Packages map[string]*types.Package 45 | PackageName string 46 | }{ 47 | FieldResolvers: parsedTree.ResolverTree.FieldResolvers, 48 | Rewriter: r, 49 | Packages: pkgs, 50 | PackageName: c.Resolver.Package, 51 | }) 52 | if err != nil { 53 | return err 54 | } 55 | return nil 56 | } 57 | return errors.New("Resolver file pattern invalid") 58 | } 59 | 60 | func fieldResolverBody(key string, rewriter *rewriter.Rewriter) string { 61 | if val, ok := rewriter.RewriteBodies[key]; ok { 62 | return val 63 | } else { 64 | return ` 65 | return nil, nil 66 | ` 67 | } 68 | } 69 | 70 | var fieldResolverTemplate = template.Must(template.New("field-resolver").Funcs(template.FuncMap{ 71 | "ref": modelRef, 72 | "path": pkgPath, 73 | "pointer": pointer, 74 | "body": fieldResolverBody, 75 | "is": is, 76 | }).Parse(` 77 | package {{.PackageName}} 78 | 79 | import( 80 | {{- range $pkg := .Packages }} 81 | "{{ $pkg | path }}"{{- end}} 82 | ) 83 | 84 | type FieldResolverInterface interface { 85 | {{- range $fieldResolver := .FieldResolvers}} 86 | {{$fieldResolver.Parent.Name }}_{{$fieldResolver.Field.Name}}(ctx context.Context, parents []{{ pointer $fieldResolver.Parent.GoType false }}, authHeader api.AuthHeader) ([]{{ pointer $fieldResolver.Field.GoType $fieldResolver.Field.IsArray }}, *api.LambdaError){{ end }} 87 | } 88 | 89 | type FieldResolver struct { 90 | *Resolver 91 | } 92 | 93 | {{- range $fieldResolver := .FieldResolvers}} 94 | func (f *FieldResolver) {{$fieldResolver.Parent.Name }}_{{$fieldResolver.Field.Name}}(ctx context.Context, parents []{{ pointer $fieldResolver.Parent.GoType false }}, authHeader api.AuthHeader) ([]{{ pointer $fieldResolver.Field.GoType $fieldResolver.Field.IsArray }}, *api.LambdaError) { {{ body (printf "%s_%s" $fieldResolver.Parent.Name $fieldResolver.Field.Name) $.Rewriter }}} 95 | {{ end }} 96 | 97 | {{- range $key, $depBody := .Rewriter.DeprecatedBodies }} 98 | {{ if and (not (is $key "Query_")) (not (is $key "Mutation_")) (not (is $key "Middleware_")) }} 99 | /* {{ $depBody }} */ 100 | {{ end }} 101 | {{ end }} 102 | `)) 103 | -------------------------------------------------------------------------------- /codegen/generator/generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "fmt" 5 | "go/types" 6 | "strings" 7 | "unicode" 8 | 9 | "github.com/pkg/errors" 10 | "github.com/schartey/dgraph-lambda-go/codegen/config" 11 | "github.com/schartey/dgraph-lambda-go/codegen/graphql" 12 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 13 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 14 | ) 15 | 16 | func Generate(c *config.Config, p *parser.Tree, r *rewriter.Rewriter) error { 17 | 18 | if err := generateModel(c, p); err != nil { 19 | return errors.Wrap(err, "Could not generate model") 20 | } 21 | if err := generateFieldResolvers(c, p, r); err != nil { 22 | return errors.Wrap(err, "Could not generate field resolvers") 23 | } 24 | if err := generateQueryResolvers(c, p, r); err != nil { 25 | return errors.Wrap(err, "Could not generate query resolvers") 26 | } 27 | if err := generateMutationResolvers(c, p, r); err != nil { 28 | return errors.Wrap(err, "Could not generate mutation resolvers") 29 | } 30 | if err := generateMiddleware(c, p, r); err != nil { 31 | return errors.Wrap(err, "Could not generate middleware resolvers") 32 | } 33 | if err := generateWebhook(c, p, r); err != nil { 34 | return errors.Wrap(err, "Could not generate webhook resolvers") 35 | } 36 | if err := generateExecuter(c, p, r); err != nil { 37 | return errors.Wrap(err, "Could not generate executer") 38 | } 39 | return nil 40 | } 41 | 42 | func resolverRef(t *parser.GoType) string { 43 | if t.TypeName.Pkg() != nil { 44 | /*for _, te := range autobind { 45 | if te == t.TypeName.Pkg().Path() { 46 | return fmt.Sprintf("%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 47 | } 48 | }*/ 49 | if t.TypeName.Exported() { 50 | return fmt.Sprintf("%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 51 | } 52 | } 53 | return t.TypeName.Name() 54 | } 55 | 56 | func pkgPath(t *types.Package) string { 57 | return t.Path() 58 | } 59 | 60 | func title(t string) string { 61 | return strings.Title(t) 62 | } 63 | 64 | func untitle(s string) string { 65 | if len(s) == 0 { 66 | return s 67 | } 68 | 69 | r := []rune(s) 70 | r[0] = unicode.ToLower(r[0]) 71 | return string(r) 72 | } 73 | 74 | func typeName(t *types.TypeName) string { 75 | return t.Name() 76 | } 77 | 78 | func pointer(t *parser.GoType, isArray bool) string { 79 | if !t.TypeName.Exported() { 80 | return t.TypeName.Name() 81 | } else { 82 | if isArray { 83 | return fmt.Sprintf("[]*%s", resolverRef(t)) 84 | } else { 85 | return fmt.Sprintf("*%s", resolverRef(t)) 86 | } 87 | } 88 | } 89 | 90 | func args(args []*parser.Argument) string { 91 | var arglist []string 92 | 93 | for _, arg := range args { 94 | arglist = append(arglist, fmt.Sprintf("%s", arg.Name)) 95 | } 96 | return strings.Join(arglist, ",") 97 | } 98 | 99 | func argsW(args []*parser.Argument) string { 100 | var arglist []string 101 | 102 | for _, arg := range args { 103 | arglist = append(arglist, fmt.Sprintf("%s %s", arg.Name, pointer(arg.GoType, arg.IsArray))) 104 | } 105 | return strings.Join(arglist, ",") 106 | } 107 | 108 | func returnValue(t *parser.GoType, isArray bool) string { 109 | defaultValue, err := graphql.GetDefaultStringValueForType(t.TypeName.Name()) 110 | fmt.Println(t.TypeName.Name()) 111 | if err != nil || isArray { 112 | return "nil" 113 | } else { 114 | return defaultValue 115 | } 116 | } 117 | 118 | func body(t *parser.GoType, isArray bool, key string, rewriter *rewriter.Rewriter) string { 119 | if val, ok := rewriter.RewriteBodies[key]; ok { 120 | return val 121 | } else { 122 | return fmt.Sprintf(` 123 | return %s, nil 124 | `, returnValue(t, isArray)) 125 | } 126 | } 127 | 128 | func middlewareBody(key string, rewriter *rewriter.Rewriter) string { 129 | if val, ok := rewriter.RewriteBodies[key]; ok { 130 | return val 131 | } else { 132 | return ` 133 | return nil 134 | ` 135 | } 136 | } 137 | 138 | func is(key string, resolverType string) bool { 139 | return strings.HasPrefix(key, resolverType) 140 | } 141 | -------------------------------------------------------------------------------- /codegen/generator/init.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "os" 5 | "path" 6 | "path/filepath" 7 | "strings" 8 | "text/template" 9 | 10 | "github.com/pkg/errors" 11 | "github.com/schartey/dgraph-lambda-go/codegen/config" 12 | ) 13 | 14 | func GenerateConfig(filename string) error { 15 | if t, err := os.Open(filename); os.IsNotExist(err) { 16 | f, err := createFile(filename) 17 | if err != nil { 18 | return errors.Wrap(err, "Could not create config: "+filename) 19 | } 20 | 21 | lambdaTemplate.Execute(f, struct{}{}) 22 | f.Close() 23 | } else { 24 | t.Close() 25 | } 26 | return nil 27 | } 28 | 29 | func Init(config *config.Config) error { 30 | 31 | f, err := createFile(config.Exec.Filename) 32 | if err != nil { 33 | return err 34 | } 35 | template.Must(template.New("exec").Parse("package "+config.Exec.Package)).Execute(f, struct{}{}) 36 | f.Close() 37 | 38 | f, err = createFile(config.Model.Filename) 39 | if err != nil { 40 | return err 41 | } 42 | template.Must(template.New("model").Parse("package "+config.Model.Package)).Execute(f, struct{}{}) 43 | f.Close() 44 | f, err = createFile(config.Resolver.Dir) 45 | if err != nil { 46 | return err 47 | } 48 | f.Close() 49 | 50 | // Generate Resolver 51 | f, err = createFile(path.Join(config.Resolver.Dir, "resolver.go")) 52 | if err != nil { 53 | return err 54 | } 55 | 56 | resolverTemplate.Execute(f, struct { 57 | Package string 58 | }{ 59 | Package: config.Resolver.Package, 60 | }) 61 | f.Close() 62 | 63 | f, err = os.Create("server.go") 64 | if err != nil { 65 | return err 66 | } 67 | 68 | serverTemplate.Execute(f, struct { 69 | ResolverPath string 70 | ResolverPackage string 71 | GeneratedPath string 72 | GeneratedPackage string 73 | Standalone bool 74 | }{ 75 | ResolverPath: path.Join(config.Root, config.Resolver.Dir), 76 | ResolverPackage: config.Resolver.Package, 77 | GeneratedPath: path.Join(config.Root, path.Dir(config.Exec.Filename)), 78 | GeneratedPackage: config.Exec.Package, 79 | Standalone: config.Server.Standalone, 80 | }) 81 | f.Close() 82 | 83 | return nil 84 | } 85 | 86 | func createFile(p string) (*os.File, error) { 87 | path := p 88 | file := "" 89 | if strings.Contains(filepath.Base(p), ".") { 90 | path = filepath.Dir(p) 91 | file = filepath.Base(p) 92 | } 93 | 94 | if err := os.MkdirAll(path, os.ModePerm); err != nil { 95 | print(err.Error()) 96 | return nil, err 97 | } 98 | if file == "" { 99 | return nil, nil 100 | } 101 | return os.Create(p) 102 | } 103 | 104 | var resolverTemplate = template.Must(template.New("resolver").Parse(`package {{ .Package }} 105 | 106 | // Add objects to your desire 107 | type Resolver struct { 108 | }`)) 109 | 110 | var lambdaTemplate = template.Must(template.New("lambda").Parse(`schema: 111 | - ./*.graphql 112 | 113 | exec: 114 | filename: lambda/generated/generated.go 115 | package: generated 116 | 117 | model: 118 | filename: lambda/model/models_gen.go 119 | package: model 120 | 121 | autobind: 122 | # - "github.com/schartey/dgraph-lambda-go/examples/models" 123 | 124 | resolver: 125 | dir: lambda/resolvers 126 | package: resolvers 127 | filename_template: "{resolver}.resolver.go" # also allow "{name}.resolvers.go" 128 | 129 | server: 130 | standalone: true`)) 131 | 132 | var serverTemplate = template.Must(template.New("server").Parse(`package main 133 | 134 | import ( 135 | {{ if .Standalone }} 136 | "context" 137 | "fmt" 138 | "os" 139 | "os/signal" 140 | "sync" 141 | "time" 142 | {{ end }} 143 | {{ if not .Standalone }} 144 | "fmt" 145 | "net/http" 146 | "github.com/go-chi/chi" 147 | {{ end }} 148 | 149 | "github.com/schartey/dgraph-lambda-go/api" 150 | "{{ .GeneratedPath }}" 151 | "{{ .ResolverPath }}" 152 | ) 153 | 154 | func main() { 155 | {{ if .Standalone }} 156 | // Catch interrupt signal 157 | c := make(chan os.Signal, 1) 158 | signal.Notify(c, os.Interrupt) 159 | 160 | // WaitGroup for server shutdown 161 | wg := &sync.WaitGroup{} 162 | wg.Add(1) 163 | 164 | resolver := &{{ .ResolverPackage }}.Resolver{} 165 | executer := {{ .GeneratedPackage }}.NewExecuter(resolver) 166 | lambda := api.New(executer) 167 | srv, err := lambda.Serve(wg) 168 | if err != nil { 169 | fmt.Println(err) 170 | } 171 | 172 | // Interrupt signal received 173 | <-c 174 | fmt.Println("Shutdown request (Ctrl-C) caught.") 175 | fmt.Println("Shutting down...") 176 | 177 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 178 | defer cancel() 179 | 180 | // Shutdown server 181 | if err := srv.Shutdown(ctx); err != nil { 182 | fmt.Println(err) 183 | } 184 | // Wait for server shutdown 185 | wg.Wait() 186 | {{ else }} 187 | r := chi.NewRouter() 188 | 189 | resolver := &{{ .ResolverPackage }}.Resolver{} 190 | executer := {{ .GeneratedPackage }}.NewExecuter(resolver) 191 | lambda := api.New(executer) 192 | 193 | r.Post("/graphql-worker", lambda.Route) 194 | 195 | fmt.Println("Lambda listening on 8686") 196 | fmt.Println(http.ListenAndServe(":8686", r)) 197 | 198 | {{ end }} 199 | } 200 | `)) 201 | -------------------------------------------------------------------------------- /codegen/generator/middleware_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "errors" 5 | "go/types" 6 | "os" 7 | "path" 8 | "text/template" 9 | 10 | "github.com/schartey/dgraph-lambda-go/codegen/config" 11 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 12 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 13 | ) 14 | 15 | func generateMiddleware(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 16 | if c.ResolverFilename == "resolver" { 17 | 18 | fileName := path.Join(c.Resolver.Dir, "middleware.resolver.go") 19 | f, err := os.Create(fileName) 20 | if err != nil { 21 | return err 22 | } 23 | defer f.Close() 24 | 25 | pkgs := make(map[string]*types.Package) 26 | 27 | if len(parsedTree.Middleware) > 0 { 28 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 29 | } 30 | 31 | err = middlewareResolverTemplate.Execute(f, struct { 32 | Middleware map[string]string 33 | Rewriter *rewriter.Rewriter 34 | Packages map[string]*types.Package 35 | PackageName string 36 | }{ 37 | Middleware: parsedTree.Middleware, 38 | Rewriter: r, 39 | Packages: pkgs, 40 | PackageName: c.Resolver.Package, 41 | }) 42 | if err != nil { 43 | return err 44 | } 45 | return nil 46 | } 47 | return errors.New("Resolver file pattern invalid") 48 | } 49 | 50 | var middlewareResolverTemplate = template.Must(template.New("middleware-resolver").Funcs(template.FuncMap{ 51 | "path": pkgPath, 52 | "body": middlewareBody, 53 | "is": is, 54 | }).Parse(` 55 | package {{.PackageName}} 56 | 57 | import( 58 | {{- range $pkg := .Packages }} 59 | "{{ $pkg | path }}"{{- end}} 60 | ) 61 | 62 | type MiddlewareResolverInterface interface { 63 | {{- range $middleware := .Middleware}} 64 | Middleware_{{$middleware}}(mc *api.MiddlewareContext) *api.LambdaError{{ end }} 65 | } 66 | 67 | type MiddlewareResolver struct { 68 | *Resolver 69 | } 70 | 71 | {{ range $middleware := .Middleware}} 72 | func (m *MiddlewareResolver) Middleware_{{$middleware}}(mc *api.MiddlewareContext) *api.LambdaError { {{ body (printf "Middleware_%s" $middleware) $.Rewriter }}} 73 | {{ end }} 74 | 75 | {{- range $key, $depBody := .Rewriter.DeprecatedBodies }} 76 | {{ if is $key "Middleware_" }} 77 | /* {{ $depBody }} */ 78 | {{ end }} 79 | {{ end }} 80 | `)) 81 | -------------------------------------------------------------------------------- /codegen/generator/model_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "fmt" 5 | "go/types" 6 | "os" 7 | "text/template" 8 | 9 | "github.com/schartey/dgraph-lambda-go/codegen/config" 10 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 11 | "golang.org/x/tools/go/packages" 12 | ) 13 | 14 | var defaultPackage *packages.Package 15 | 16 | func generateModel(c *config.Config, parsedTree *parser.Tree) error { 17 | 18 | defaultPackage = c.DefaultModelPackage 19 | 20 | f, err := os.Create(c.Model.Filename) 21 | if err != nil { 22 | return err 23 | } 24 | defer f.Close() 25 | 26 | var pkgs = make(map[string]*types.Package) 27 | var models = make(map[string]*parser.Model) 28 | var enums = make(map[string]*parser.Enum) 29 | var interfaces = make(map[string]*parser.Interface) 30 | var scalars = make(map[string]*parser.Scalar) 31 | 32 | for _, m := range parsedTree.ModelTree.Models { 33 | if m.GoType.TypeName.Pkg().Path() == c.DefaultModelPackage.PkgPath && !m.GoType.Autobind { 34 | models[m.Name] = m 35 | } 36 | for _, f := range m.Fields { 37 | if f.TypeName.Exported() && f.GoType.TypeName.Pkg().Path() != c.DefaultModelPackage.PkgPath { 38 | pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg() 39 | } 40 | } 41 | } 42 | for _, m := range parsedTree.ModelTree.Enums { 43 | if m.TypeName.Exported() && m.GoType.TypeName.Pkg().Path() == c.DefaultModelPackage.PkgPath && !m.GoType.Autobind { 44 | enums[m.Name] = m 45 | } 46 | } 47 | for _, m := range parsedTree.ModelTree.Interfaces { 48 | if m.TypeName.Exported() && m.GoType.TypeName.Pkg().Path() == c.DefaultModelPackage.PkgPath && !m.GoType.Autobind { 49 | interfaces[m.Name] = m 50 | } 51 | } 52 | for _, m := range parsedTree.ModelTree.Scalars { 53 | if m.TypeName.Exported() && m.GoType.TypeName.Pkg().Path() == c.DefaultModelPackage.PkgPath && !m.GoType.Autobind { 54 | scalars[m.Name] = m 55 | } 56 | } 57 | if len(enums) > 0 { 58 | pkgs["fmt"] = types.NewPackage("fmt", "fmt") 59 | pkgs["strconv"] = types.NewPackage("strconv", "strconv") 60 | pkgs["io"] = types.NewPackage("io", "io") 61 | } 62 | 63 | err = modelTemplate.Execute(f, struct { 64 | Interfaces map[string]*parser.Interface 65 | Enums map[string]*parser.Enum 66 | Scalars map[string]*parser.Scalar 67 | Models map[string]*parser.Model 68 | Packages map[string]*types.Package 69 | PackageName string 70 | }{ 71 | Interfaces: interfaces, 72 | Enums: enums, 73 | Scalars: parsedTree.ModelTree.Scalars, 74 | Models: models, 75 | Packages: pkgs, 76 | PackageName: c.Model.Package, 77 | }) 78 | if err != nil { 79 | return err 80 | } 81 | return nil 82 | } 83 | 84 | func modelRef(t *parser.GoType, isArray bool) string { 85 | if t.TypeName.Exported() && t.TypeName.Pkg().Path() != defaultPackage.PkgPath { 86 | if isArray { 87 | return fmt.Sprintf("[]*%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 88 | } else { 89 | return fmt.Sprintf("*%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 90 | } 91 | } 92 | if t.TypeName.Exported() { 93 | if isArray { 94 | return fmt.Sprintf("[]*%s", t.TypeName.Name()) 95 | } else { 96 | return fmt.Sprintf("*%s", t.TypeName.Name()) 97 | } 98 | } 99 | if isArray { 100 | return fmt.Sprintf("[]%s", t.TypeName.Name()) 101 | } else { 102 | return t.TypeName.Name() 103 | } 104 | } 105 | 106 | var modelTemplate = template.Must(template.New("model").Funcs(template.FuncMap{ 107 | "ref": modelRef, 108 | "path": pkgPath, 109 | "title": title, 110 | }).Parse(`package {{.PackageName}} 111 | 112 | import( 113 | {{- range $pkg := .Packages }} 114 | "{{ $pkg | path }}"{{- end}} 115 | ) 116 | 117 | {{- range $model := .Interfaces }} 118 | type {{.Name }} interface { 119 | Is{{.Name }}() 120 | } 121 | {{- end }} 122 | {{- range $model := .Models }} 123 | type {{ .Name }} struct { 124 | {{- range $field := .Fields }} 125 | {{- with .Description }} 126 | {{- end}} 127 | {{ $field.Name | title }} {{ ref $field.GoType $field.IsArray }} ` + "`{{$field.Tag}}`" + ` 128 | {{- end }} 129 | } 130 | {{- end }} 131 | {{ range $enum := .Enums }} 132 | type {{$enum.Name }} string 133 | const ( 134 | {{- range $value := $enum.Values}} 135 | {{- with $value.Description}} 136 | {{- end}} 137 | {{ $enum.Name }}{{ $value.Name }} {{$enum.Name }} = "{{$value.Name}}" 138 | {{- end }} 139 | ) 140 | 141 | var All{{$enum.Name }} = []{{ $enum.Name }}{ 142 | {{- range $value := $enum.Values}} 143 | {{$enum.Name }}{{ .Name }}, 144 | {{- end }} 145 | } 146 | 147 | func (e {{$enum.Name }}) IsValid() bool { 148 | switch e { 149 | case {{ range $index, $element := $enum.Values}}{{if $index}},{{end}}{{ $enum.Name }}{{ $element.Name }}{{end}}: 150 | return true 151 | } 152 | return false 153 | } 154 | 155 | func (e {{$enum.Name }}) String() string { 156 | return string(e) 157 | } 158 | 159 | func (e *{{$enum.Name }}) UnmarshalGQL(v interface{}) error { 160 | str, ok := v.(string) 161 | if !ok { 162 | return fmt.Errorf("enums must be strings") 163 | } 164 | 165 | *e = {{ $enum.Name }}(str) 166 | if !e.IsValid() { 167 | return fmt.Errorf("%s is not a valid {{ $enum.Name }}", str) 168 | } 169 | return nil 170 | } 171 | 172 | func (e {{$enum.Name }}) MarshalGQL(w io.Writer) { 173 | fmt.Fprint(w, strconv.Quote(e.String())) 174 | } 175 | 176 | {{- end }} 177 | `)) 178 | -------------------------------------------------------------------------------- /codegen/generator/mutation_resolver_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "go/types" 7 | "os" 8 | "path" 9 | "text/template" 10 | 11 | "github.com/schartey/dgraph-lambda-go/codegen/config" 12 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 13 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 14 | ) 15 | 16 | func generateMutationResolvers(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 17 | if c.ResolverFilename == "resolver" { 18 | 19 | fileName := path.Join(c.Resolver.Dir, "mutation.resolver.go") 20 | f, err := os.Create(fileName) 21 | if err != nil { 22 | fmt.Println(err.Error()) 23 | } 24 | defer f.Close() 25 | 26 | pkgs := make(map[string]*types.Package) 27 | 28 | for _, m := range parsedTree.ResolverTree.Mutations { 29 | if m.Return.TypeName.Exported() { 30 | pkgs[m.Return.TypeName.Pkg().Name()] = m.Return.TypeName.Pkg() 31 | } 32 | 33 | for _, f := range m.Arguments { 34 | if f.TypeName.Exported() { 35 | pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg() 36 | } 37 | } 38 | } 39 | if len(parsedTree.ResolverTree.Mutations) > 0 { 40 | pkgs["context"] = types.NewPackage("context", "context") 41 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 42 | } 43 | 44 | err = mutationResolverTemplate.Execute(f, struct { 45 | MutationResolvers map[string]*parser.Mutation 46 | Rewriter *rewriter.Rewriter 47 | Packages map[string]*types.Package 48 | PackageName string 49 | }{ 50 | MutationResolvers: parsedTree.ResolverTree.Mutations, 51 | Rewriter: r, 52 | Packages: pkgs, 53 | PackageName: c.Resolver.Package, 54 | }) 55 | if err != nil { 56 | return err 57 | } 58 | return nil 59 | } 60 | return errors.New("Resolver file pattern invalid") 61 | } 62 | 63 | var mutationResolverTemplate = template.Must(template.New("mutation-resolver").Funcs(template.FuncMap{ 64 | "ref": returnRef, 65 | "path": pkgPath, 66 | "pointer": pointer, 67 | "argsW": argsW, 68 | "body": body, 69 | "is": is, 70 | }).Parse(` 71 | package {{.PackageName}} 72 | 73 | import( 74 | {{- range $pkg := .Packages }} 75 | "{{ $pkg | path }}"{{- end}} 76 | ) 77 | 78 | type MutationResolverInterface interface { 79 | {{- range $mutationResolver := .MutationResolvers}} 80 | Mutation_{{$mutationResolver.Name}}(ctx context.Context{{ if ne (len $mutationResolver.Arguments) 0}}, {{ $mutationResolver.Arguments | argsW }}{{ end }}, authHeader api.AuthHeader) ({{ ref $mutationResolver.Return.GoType $mutationResolver.Return.IsArray }}, *api.LambdaError){{ end }} 81 | } 82 | 83 | type MutationResolver struct { 84 | *Resolver 85 | } 86 | 87 | {{- range $mutationResolver := .MutationResolvers}} 88 | func (q *MutationResolver) Mutation_{{$mutationResolver.Name}}(ctx context.Context{{ if ne (len $mutationResolver.Arguments) 0}}, {{ $mutationResolver.Arguments | argsW }}{{ end }}, authHeader api.AuthHeader) ({{ ref $mutationResolver.Return.GoType $mutationResolver.Return.IsArray }}, *api.LambdaError) { {{ body $mutationResolver.Return.GoType $mutationResolver.Return.IsArray (printf "Mutation_%s" $mutationResolver.Name) $.Rewriter }}} 89 | {{ end }} 90 | 91 | {{- range $key, $depBody := .Rewriter.DeprecatedBodies }} 92 | {{ if is $key "Mutation_" }} 93 | /* {{ $depBody }} */ 94 | {{ end }} 95 | {{ end }} 96 | `)) 97 | -------------------------------------------------------------------------------- /codegen/generator/query_resolver_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "go/types" 7 | "os" 8 | "path" 9 | "text/template" 10 | 11 | "github.com/schartey/dgraph-lambda-go/codegen/config" 12 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 13 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 14 | ) 15 | 16 | func generateQueryResolvers(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 17 | 18 | if c.ResolverFilename == "resolver" { 19 | 20 | fileName := path.Join(c.Resolver.Dir, "query.resolver.go") 21 | f, err := os.Create(fileName) 22 | if err != nil { 23 | return err 24 | } 25 | defer f.Close() 26 | 27 | pkgs := make(map[string]*types.Package) 28 | 29 | for _, m := range parsedTree.ResolverTree.Queries { 30 | if m.Return.TypeName.Exported() { 31 | pkgs[m.Return.TypeName.Pkg().Name()] = m.Return.TypeName.Pkg() 32 | } 33 | 34 | for _, f := range m.Arguments { 35 | if f.TypeName.Exported() { 36 | pkgs[f.GoType.TypeName.Pkg().Name()] = f.GoType.TypeName.Pkg() 37 | } 38 | } 39 | } 40 | if len(parsedTree.ResolverTree.Queries) > 0 { 41 | pkgs["context"] = types.NewPackage("context", "context") 42 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 43 | } 44 | 45 | err = queryResolverTemplate.Execute(f, struct { 46 | QueryResolvers map[string]*parser.Query 47 | Rewriter *rewriter.Rewriter 48 | Packages map[string]*types.Package 49 | PackageName string 50 | }{ 51 | QueryResolvers: parsedTree.ResolverTree.Queries, 52 | Rewriter: r, 53 | Packages: pkgs, 54 | PackageName: c.Resolver.Package, 55 | }) 56 | if err != nil { 57 | return err 58 | } 59 | return nil 60 | } 61 | return errors.New("Resolver file pattern invalid") 62 | } 63 | 64 | func returnRef(t *parser.GoType, isArray bool) string { 65 | if t.TypeName.Pkg() != nil { 66 | if t.TypeName.Exported() { 67 | if isArray { 68 | return fmt.Sprintf("[]*%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 69 | } else { 70 | return fmt.Sprintf("*%s.%s", t.TypeName.Pkg().Name(), t.TypeName.Name()) 71 | } 72 | } 73 | } 74 | if isArray { 75 | return fmt.Sprintf("[]%s", t.TypeName.Name()) 76 | } else { 77 | return t.TypeName.Name() 78 | } 79 | } 80 | 81 | var queryResolverTemplate = template.Must(template.New("query-resolver").Funcs(template.FuncMap{ 82 | "ref": returnRef, 83 | "path": pkgPath, 84 | "pointer": pointer, 85 | "argsW": argsW, 86 | "body": body, 87 | "is": is, 88 | }).Parse(` 89 | package {{.PackageName}} 90 | 91 | import( 92 | {{- range $pkg := .Packages }} 93 | "{{ $pkg | path }}"{{- end}} 94 | ) 95 | 96 | type QueryResolverInterface interface { 97 | {{- range $queryResolver := .QueryResolvers}} 98 | Query_{{$queryResolver.Name}}(ctx context.Context{{ if ne (len $queryResolver.Arguments) 0}}, {{ $queryResolver.Arguments | argsW }}{{ end }}, authHeader api.AuthHeader) ({{ ref $queryResolver.Return.GoType $queryResolver.Return.IsArray }}, *api.LambdaError){{ end }} 99 | } 100 | 101 | type QueryResolver struct { 102 | *Resolver 103 | } 104 | 105 | {{- range $queryResolver := .QueryResolvers}} 106 | func (q *QueryResolver) Query_{{$queryResolver.Name}}(ctx context.Context{{ if ne (len $queryResolver.Arguments) 0}}, {{ $queryResolver.Arguments | argsW }}{{ end }}, authHeader api.AuthHeader) ({{ ref $queryResolver.Return.GoType $queryResolver.Return.IsArray }}, *api.LambdaError) { {{ body $queryResolver.Return.GoType $queryResolver.Return.IsArray (printf "Query_%s" $queryResolver.Name) $.Rewriter }}} 107 | {{ end }} 108 | 109 | {{- range $key, $depBody := .Rewriter.DeprecatedBodies }} 110 | {{ if is $key "Query_" }} 111 | /* {{ $depBody }} */ 112 | {{ end }} 113 | {{ end }} 114 | `)) 115 | -------------------------------------------------------------------------------- /codegen/generator/webhook_generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "errors" 5 | "go/types" 6 | "os" 7 | "path" 8 | "text/template" 9 | 10 | "github.com/schartey/dgraph-lambda-go/codegen/config" 11 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 12 | "github.com/schartey/dgraph-lambda-go/codegen/rewriter" 13 | ) 14 | 15 | func generateWebhook(c *config.Config, parsedTree *parser.Tree, r *rewriter.Rewriter) error { 16 | if c.ResolverFilename == "resolver" { 17 | 18 | fileName := path.Join(c.Resolver.Dir, "webhook.resolver.go") 19 | f, err := os.Create(fileName) 20 | if err != nil { 21 | return err 22 | } 23 | defer f.Close() 24 | 25 | pkgs := make(map[string]*types.Package) 26 | 27 | var models = make(map[string]*parser.Model) 28 | 29 | for _, m := range parsedTree.ModelTree.Models { 30 | if len(m.LambdaOnMutate) > 0 { 31 | models[m.Name] = m 32 | //pkgs[m.TypeName.Pkg().Name()] = m.TypeName.Pkg() 33 | } 34 | } 35 | 36 | if len(models) > 0 { 37 | pkgs["context"] = types.NewPackage("context", "context") 38 | pkgs["api"] = types.NewPackage("github.com/schartey/dgraph-lambda-go/api", "api") 39 | } 40 | 41 | err = webhookResolverTemplate.Execute(f, struct { 42 | Models map[string]*parser.Model 43 | Rewriter *rewriter.Rewriter 44 | Packages map[string]*types.Package 45 | PackageName string 46 | }{ 47 | Models: models, 48 | Rewriter: r, 49 | Packages: pkgs, 50 | PackageName: c.Resolver.Package, 51 | }) 52 | if err != nil { 53 | return err 54 | } 55 | return nil 56 | } 57 | return errors.New("Resolver file pattern invalid") 58 | } 59 | 60 | var webhookResolverTemplate = template.Must(template.New("webhook-resolver").Funcs(template.FuncMap{ 61 | "path": pkgPath, 62 | "body": middlewareBody, 63 | "typeName": typeName, 64 | "is": is, 65 | }).Parse(` 66 | package {{.PackageName}} 67 | 68 | import( 69 | {{- range $pkg := .Packages }} 70 | "{{ $pkg | path }}"{{- end}} 71 | ) 72 | 73 | type WebhookResolverInterface interface { 74 | {{- range $model := .Models}} 75 | Webhook_{{ $model.TypeName | typeName }}(ctx context.Context, event *api.Event) *api.LambdaError{{ end }} 76 | } 77 | 78 | type WebhookResolver struct { 79 | *Resolver 80 | } 81 | 82 | {{ range $model := .Models}} 83 | func (w *WebhookResolver) Webhook_{{ $model.TypeName | typeName }}(ctx context.Context, event *api.Event) *api.LambdaError { {{ body (printf "Webhook_%s" ($model.TypeName | typeName)) $.Rewriter }}} 84 | {{ end }} 85 | `)) 86 | -------------------------------------------------------------------------------- /codegen/graphql/dgraph.go: -------------------------------------------------------------------------------- 1 | package graphql 2 | 3 | /** 4 | This part is taken from the official DGraph Source to provide all functionality for the schema validation. 5 | **/ 6 | 7 | const ( 8 | SchemaInputs = ` 9 | """ 10 | The Int64 scalar type represents a signed 64‐bit numeric non‐fractional value. 11 | Int64 can represent values in range [-(2^63),(2^63 - 1)]. 12 | """ 13 | scalar Int64 14 | """ 15 | The Int64 scalar type represents a signed 64‐bit numeric non‐fractional value. 16 | Int64 can represent values in range [-(2^63),(2^63 - 1)]. 17 | """ 18 | scalar Password 19 | """ 20 | The DateTime scalar type represents date and time as a string in RFC3339 format. 21 | For example: "1985-04-12T23:20:50.52Z" represents 20 minutes and 50.52 seconds after the 23rd hour of April 12th, 1985 in UTC. 22 | """ 23 | scalar DateTime 24 | input IntRange{ 25 | min: Int! 26 | max: Int! 27 | } 28 | input FloatRange{ 29 | min: Float! 30 | max: Float! 31 | } 32 | input Int64Range{ 33 | min: Int64! 34 | max: Int64! 35 | } 36 | input DateTimeRange{ 37 | min: DateTime! 38 | max: DateTime! 39 | } 40 | input StringRange{ 41 | min: String! 42 | max: String! 43 | } 44 | enum DgraphIndex { 45 | int 46 | int64 47 | float 48 | bool 49 | hash 50 | exact 51 | term 52 | fulltext 53 | trigram 54 | regexp 55 | year 56 | month 57 | day 58 | hour 59 | geo 60 | } 61 | input AuthRule { 62 | and: [AuthRule] 63 | or: [AuthRule] 64 | not: AuthRule 65 | rule: String 66 | } 67 | enum HTTPMethod { 68 | GET 69 | POST 70 | PUT 71 | PATCH 72 | DELETE 73 | } 74 | enum Mode { 75 | BATCH 76 | SINGLE 77 | } 78 | input CustomHTTP { 79 | url: String! 80 | method: HTTPMethod! 81 | body: String 82 | graphql: String 83 | mode: Mode 84 | forwardHeaders: [String!] 85 | secretHeaders: [String!] 86 | introspectionHeaders: [String!] 87 | skipIntrospection: Boolean 88 | } 89 | type Point { 90 | longitude: Float! 91 | latitude: Float! 92 | } 93 | input PointRef { 94 | longitude: Float! 95 | latitude: Float! 96 | } 97 | input NearFilter { 98 | distance: Float! 99 | coordinate: PointRef! 100 | } 101 | input PointGeoFilter { 102 | near: NearFilter 103 | within: WithinFilter 104 | } 105 | type PointList { 106 | points: [Point!]! 107 | } 108 | input PointListRef { 109 | points: [PointRef!]! 110 | } 111 | type Polygon { 112 | coordinates: [PointList!]! 113 | } 114 | input PolygonRef { 115 | coordinates: [PointListRef!]! 116 | } 117 | type MultiPolygon { 118 | polygons: [Polygon!]! 119 | } 120 | input MultiPolygonRef { 121 | polygons: [PolygonRef!]! 122 | } 123 | input WithinFilter { 124 | polygon: PolygonRef! 125 | } 126 | input ContainsFilter { 127 | point: PointRef 128 | polygon: PolygonRef 129 | } 130 | input IntersectsFilter { 131 | polygon: PolygonRef 132 | multiPolygon: MultiPolygonRef 133 | } 134 | input PolygonGeoFilter { 135 | near: NearFilter 136 | within: WithinFilter 137 | contains: ContainsFilter 138 | intersects: IntersectsFilter 139 | } 140 | input GenerateQueryParams { 141 | get: Boolean 142 | query: Boolean 143 | password: Boolean 144 | aggregate: Boolean 145 | } 146 | input GenerateMutationParams { 147 | add: Boolean 148 | update: Boolean 149 | delete: Boolean 150 | } 151 | ` 152 | DirectiveDefs = ` 153 | directive @hasInverse(field: String!) on FIELD_DEFINITION 154 | directive @search(by: [DgraphIndex!]) on FIELD_DEFINITION 155 | directive @dgraph(type: String, pred: String) on OBJECT | INTERFACE | FIELD_DEFINITION 156 | directive @id(interface: Boolean) on FIELD_DEFINITION 157 | directive @withSubscription on OBJECT | INTERFACE | FIELD_DEFINITION 158 | directive @secret(field: String!, pred: String) on OBJECT | INTERFACE 159 | directive @auth( 160 | password: AuthRule 161 | query: AuthRule, 162 | add: AuthRule, 163 | update: AuthRule, 164 | delete: AuthRule) on OBJECT | INTERFACE 165 | directive @custom(http: CustomHTTP, dql: String) on FIELD_DEFINITION 166 | directive @remote on OBJECT | INTERFACE | UNION | INPUT_OBJECT | ENUM 167 | directive @remoteResponse(name: String) on FIELD_DEFINITION 168 | directive @cascade(fields: [String]) on FIELD 169 | directive @lambda on FIELD_DEFINITION 170 | directive @lambdaOnMutate(add: Boolean, update: Boolean, delete: Boolean) on OBJECT | INTERFACE 171 | directive @cacheControl(maxAge: Int!) on QUERY 172 | directive @generate( 173 | query: GenerateQueryParams, 174 | mutation: GenerateMutationParams, 175 | subscription: Boolean) on OBJECT | INTERFACE 176 | ` 177 | // see: https://www.apollographql.com/docs/federation/gateway/#custom-directive-support 178 | // So, we should only add type system directives here. 179 | // Even with type system directives, there is a bug in Apollo Federation due to which the 180 | // directives having non-scalar args cause issues in schema stitching in gateway. 181 | // See: https://github.com/apollographql/apollo-server/issues/3655 182 | // So, such directives have to be missed too. 183 | ApolloSupportedDirectiveDefs = ` 184 | directive @hasInverse(field: String!) on FIELD_DEFINITION 185 | directive @search(by: [DgraphIndex!]) on FIELD_DEFINITION 186 | directive @dgraph(type: String, pred: String) on OBJECT | INTERFACE | FIELD_DEFINITION 187 | directive @id(interface: Boolean) on FIELD_DEFINITION 188 | directive @withSubscription on OBJECT | INTERFACE | FIELD_DEFINITION 189 | directive @secret(field: String!, pred: String) on OBJECT | INTERFACE 190 | directive @remote on OBJECT | INTERFACE | UNION | INPUT_OBJECT | ENUM 191 | directive @remoteResponse(name: String) on FIELD_DEFINITION 192 | directive @lambda on FIELD_DEFINITION 193 | directive @lambdaOnMutate(add: Boolean, update: Boolean, delete: Boolean) on OBJECT | INTERFACE 194 | ` 195 | FilterInputs = ` 196 | input IntFilter { 197 | eq: Int 198 | in: [Int] 199 | le: Int 200 | lt: Int 201 | ge: Int 202 | gt: Int 203 | between: IntRange 204 | } 205 | input Int64Filter { 206 | eq: Int64 207 | in: [Int64] 208 | le: Int64 209 | lt: Int64 210 | ge: Int64 211 | gt: Int64 212 | between: Int64Range 213 | } 214 | input FloatFilter { 215 | eq: Float 216 | in: [Float] 217 | le: Float 218 | lt: Float 219 | ge: Float 220 | gt: Float 221 | between: FloatRange 222 | } 223 | input DateTimeFilter { 224 | eq: DateTime 225 | in: [DateTime] 226 | le: DateTime 227 | lt: DateTime 228 | ge: DateTime 229 | gt: DateTime 230 | between: DateTimeRange 231 | } 232 | input StringTermFilter { 233 | allofterms: String 234 | anyofterms: String 235 | } 236 | input StringRegExpFilter { 237 | regexp: String 238 | } 239 | input StringFullTextFilter { 240 | alloftext: String 241 | anyoftext: String 242 | } 243 | input StringExactFilter { 244 | eq: String 245 | in: [String] 246 | le: String 247 | lt: String 248 | ge: String 249 | gt: String 250 | between: StringRange 251 | } 252 | input StringHashFilter { 253 | eq: String 254 | in: [String] 255 | } 256 | ` 257 | 258 | ApolloSchemaExtras = ` 259 | scalar _Entity 260 | scalar _Any 261 | scalar _FieldSet 262 | type _Service { 263 | sdl: String 264 | } 265 | directive @external on FIELD_DEFINITION 266 | directive @requires(fields: _FieldSet!) on FIELD_DEFINITION 267 | directive @provides(fields: _FieldSet!) on FIELD_DEFINITION 268 | directive @key(fields: _FieldSet!) on OBJECT | INTERFACE 269 | directive @extends on OBJECT | INTERFACE 270 | ` 271 | ApolloSchemaQueries = ` 272 | extend type Query { 273 | _entities(representations: [_Any!]!): [_Entity]! 274 | _service: _Service! 275 | } 276 | ` 277 | ) 278 | -------------------------------------------------------------------------------- /codegen/graphql/schema.go: -------------------------------------------------------------------------------- 1 | package graphql 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | 7 | "github.com/pkg/errors" 8 | "github.com/vektah/gqlparser/v2" 9 | "github.com/vektah/gqlparser/v2/ast" 10 | ) 11 | 12 | func SchemaLoaderFromExternal(host string) (*ast.Schema, error) { 13 | return nil, errors.New("Not implemented") 14 | } 15 | 16 | func SchemaLoaderFromFile(path string) (*ast.Schema, error) { 17 | schemaFile, err := os.Open(path) 18 | if err != nil { 19 | return nil, errors.Wrap(err, "unable to open schema") 20 | } 21 | schemaFile.Close() 22 | 23 | schemaInput, err := ioutil.ReadFile(path) 24 | if err != nil { 25 | return nil, errors.Wrap(err, "unable to read schema") 26 | } 27 | 28 | var sources []*ast.Source 29 | 30 | sources = append(sources, &ast.Source{Input: SchemaInputs + DirectiveDefs}) 31 | sources = append(sources, &ast.Source{Name: schemaFile.Name(), Input: string(schemaInput)}) 32 | 33 | schema := gqlparser.MustLoadSchema(sources...) 34 | 35 | return schema, nil 36 | } 37 | -------------------------------------------------------------------------------- /codegen/graphql/types.go: -------------------------------------------------------------------------------- 1 | package graphql 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | "strings" 7 | "time" 8 | 9 | "github.com/twpayne/go-geom" 10 | "github.com/vektah/gqlparser/v2/ast" 11 | ) 12 | 13 | var inbuiltTypeToDgraph = map[string]string{ 14 | // ID is interally int64, but is represented by hex string 15 | // "ID": "uid", 16 | "ID": "string", 17 | "Boolean": "bool", 18 | "Int": "int", 19 | "Int64": "int", 20 | "Float": "float", 21 | "String": "string", 22 | "DateTime": "dateTime", 23 | "Password": "password", 24 | "Point": "geo", 25 | "Polygon": "geo", 26 | "MultiPolygon": "geo", 27 | } 28 | 29 | var defaultReturnForType = map[string]string{ 30 | "string": "\"\"", 31 | "int": "0", 32 | "int64": "0", 33 | "bool": "false", 34 | "float": "0.0", 35 | "float64": "0.0", 36 | } 37 | 38 | var bytes []byte 39 | var i int64 40 | var f float64 41 | var b bool 42 | var t time.Time 43 | var s string 44 | var g geom.T 45 | var ui uint64 46 | 47 | var typeNameMap = map[string]interface{}{ 48 | "default": &s, 49 | "binary": &bytes, 50 | "int": &i, 51 | "float": &f, 52 | "bool": &b, 53 | "datetime": &t, 54 | "geo": &g, 55 | "uid": &ui, 56 | "string": &s, 57 | "password": &s, 58 | } 59 | 60 | type GoTypeDefinition struct { 61 | TypeName string 62 | PkgName string 63 | } 64 | 65 | func SchemaDefToGoDef(def *ast.Definition) (pkgPath string, typeName string, err error) { 66 | dgraphTypeName := strings.ToLower(inbuiltTypeToDgraph[def.Name]) 67 | t, ok := typeNameMap[dgraphTypeName] 68 | 69 | if !ok { 70 | return pkgPath, typeName, errors.New("TypeId not found") 71 | } 72 | reflectType := reflect.Indirect(reflect.ValueOf(t)).Type() 73 | 74 | pkgPath = reflectType.PkgPath() 75 | typeName = reflectType.Name() 76 | 77 | return pkgPath, typeName, nil 78 | } 79 | 80 | func IsArray(name string) bool { 81 | return strings.HasPrefix(name, "[") && (strings.HasSuffix(name, "]") || strings.HasSuffix(name, "]!")) 82 | } 83 | 84 | func IsDgraphType(name string) bool { 85 | return inbuiltTypeToDgraph[name] != "" 86 | } 87 | 88 | func GetDefaultStringValueForType(name string) (string, error) { 89 | if val, ok := defaultReturnForType[name]; !ok { 90 | return "", errors.New("Could not find default value") 91 | } else { 92 | return val, nil 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /codegen/parser/parser.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "go/types" 8 | "regexp" 9 | 10 | "github.com/schartey/dgraph-lambda-go/codegen/graphql" 11 | "github.com/schartey/dgraph-lambda-go/internal" 12 | "github.com/vektah/gqlparser/v2/ast" 13 | ) 14 | 15 | var middlewareRegex = regexp.MustCompile(`@middleware\(([^)]+)\)`) 16 | 17 | type LambdaOnMutateEvent string 18 | 19 | const ( 20 | ADD LambdaOnMutateEvent = "add" 21 | UPDATE LambdaOnMutateEvent = "update" 22 | DELETE LambdaOnMutateEvent = "delete" 23 | ) 24 | 25 | type GoType struct { 26 | Autobind bool 27 | TypeName *types.TypeName 28 | } 29 | 30 | type Scalar struct { 31 | *GoType 32 | Name string 33 | Description string 34 | } 35 | 36 | type Enum struct { 37 | *GoType 38 | Name string 39 | Description string 40 | Values []*EnumValue 41 | } 42 | 43 | type EnumValue struct { 44 | Name string 45 | Description string 46 | } 47 | 48 | type Interface struct { 49 | *GoType 50 | Name string 51 | Description string 52 | } 53 | 54 | type Field struct { 55 | *GoType 56 | Name string 57 | Description string 58 | Tag string 59 | IsArray bool 60 | } 61 | 62 | type Model struct { 63 | *GoType 64 | Name string 65 | Description string 66 | Fields []*Field 67 | Implements []*GoType 68 | LambdaOnMutate []LambdaOnMutateEvent 69 | } 70 | 71 | type Argument struct { 72 | *GoType 73 | Name string 74 | IsArray bool 75 | } 76 | 77 | type Return struct { 78 | *GoType 79 | IsArray bool 80 | } 81 | 82 | type Query struct { 83 | Name string 84 | Description string 85 | Arguments []*Argument 86 | Return *Return 87 | Middleware []string 88 | } 89 | 90 | type Mutation struct { 91 | Name string 92 | Description string 93 | Arguments []*Argument 94 | Return *Return 95 | Middleware []string 96 | } 97 | 98 | type Parent struct { 99 | *GoType 100 | Name string 101 | } 102 | 103 | type FieldResolver struct { 104 | Field *Field 105 | Parent *Parent 106 | Middleware []string 107 | } 108 | 109 | type Tree struct { 110 | ModelTree *ModelTree 111 | ResolverTree *ResolverTree 112 | Middleware map[string]string 113 | } 114 | 115 | type ModelTree struct { 116 | Interfaces map[string]*Interface 117 | Models map[string]*Model 118 | Enums map[string]*Enum 119 | Scalars map[string]*Scalar 120 | } 121 | 122 | type ResolverTree struct { 123 | FieldResolvers map[string]*FieldResolver 124 | Queries map[string]*Query 125 | Mutations map[string]*Mutation 126 | } 127 | 128 | type Parser struct { 129 | schema *ast.Schema 130 | tree *Tree 131 | packages *internal.Packages 132 | force []string 133 | } 134 | 135 | func NewParser(schema *ast.Schema, packages *internal.Packages, force []string) *Parser { 136 | return &Parser{schema: schema, tree: &Tree{ 137 | ModelTree: &ModelTree{ 138 | Interfaces: make(map[string]*Interface), 139 | Models: make(map[string]*Model), 140 | Enums: make(map[string]*Enum), 141 | Scalars: make(map[string]*Scalar), 142 | }, 143 | ResolverTree: &ResolverTree{ 144 | FieldResolvers: make(map[string]*FieldResolver), 145 | Queries: make(map[string]*Query), 146 | Mutations: make(map[string]*Mutation), 147 | }, 148 | Middleware: make(map[string]string), 149 | }, 150 | packages: packages, 151 | force: force, 152 | } 153 | } 154 | 155 | func (p *Parser) Parse() (*Tree, error) { 156 | for _, schemaType := range p.schema.Types { 157 | p.parseType(schemaType, true) 158 | } 159 | return p.tree, nil 160 | } 161 | 162 | func (p *Parser) parseType(schemaType *ast.Definition, mustLambda bool) (*GoType, error) { 163 | if mustLambda && !p.hasLambda(schemaType) { 164 | return nil, errors.New("type has no lambda field") 165 | } 166 | 167 | var goType *GoType 168 | var err error 169 | 170 | pkgPath, typeName, err := graphql.SchemaDefToGoDef(schemaType) 171 | if err != nil { 172 | goType = &GoType{ 173 | TypeName: types.NewTypeName(0, nil, schemaType.Name, nil), 174 | } 175 | } else { 176 | if pkgPath == "" { 177 | goType = &GoType{ 178 | TypeName: types.NewTypeName(0, nil, typeName, nil), 179 | } 180 | } else { 181 | pkg, err := p.packages.PackageFromPath(pkgPath) 182 | if err != nil { 183 | pkg, err = p.packages.Load(pkgPath) 184 | if err != nil { 185 | fmt.Println("Could not load package") 186 | } 187 | } 188 | 189 | goType = &GoType{ 190 | TypeName: types.NewTypeName(0, types.NewPackage(pkg.PkgPath, pkg.Name), typeName, nil), 191 | } 192 | } 193 | } 194 | 195 | switch schemaType.Kind { 196 | case ast.Interface, ast.Union: 197 | if it, ok := p.tree.ModelTree.Interfaces[schemaType.Name]; ok { 198 | return it.GoType, nil 199 | } 200 | it := &Interface{ 201 | Description: schemaType.Description, 202 | Name: schemaType.Name, 203 | GoType: goType, 204 | } 205 | 206 | p.tree.ModelTree.Interfaces[it.Name] = it 207 | 208 | for _, field := range schemaType.Fields { 209 | fieldType := p.schema.Types[field.Type.Name()] 210 | 211 | fieldGoType, err := p.parseType(fieldType, false) 212 | if err != nil { 213 | return nil, err 214 | } 215 | 216 | tag := `json:"` + field.Name + `"` 217 | if field.Name == "id" { 218 | tag += ` dql:"uid"` 219 | } else { 220 | tag += ` dql:"` + it.Name + "." + field.Name + `"` 221 | } 222 | 223 | modelField := &Field{ 224 | Name: field.Name, 225 | Description: field.Description, 226 | Tag: tag, 227 | GoType: fieldGoType, 228 | IsArray: graphql.IsArray(field.Type.String()), 229 | } 230 | 231 | lambdaDirective := field.Directives.ForName("lambda") 232 | 233 | if lambdaDirective != nil { 234 | out := middlewareRegex.FindAllStringSubmatch(field.Description, -1) 235 | 236 | var fieldMiddleware []string 237 | for _, i := range out { 238 | rawMiddleware := i[1] 239 | json.Unmarshal([]byte(rawMiddleware), &fieldMiddleware) 240 | } 241 | for _, m := range fieldMiddleware { 242 | p.tree.Middleware[m] = m 243 | } 244 | p.tree.ResolverTree.FieldResolvers[field.Name] = &FieldResolver{Field: modelField, Parent: &Parent{Name: schemaType.Name, GoType: it.GoType}, Middleware: fieldMiddleware} 245 | } 246 | } 247 | 248 | return it.GoType, nil 249 | 250 | case ast.Object, ast.InputObject: 251 | if schemaType == p.schema.Subscription { 252 | fmt.Println("Subscription not supported - skipping") 253 | //return nil, errors.New("subscription not supported") 254 | } 255 | if schemaType == p.schema.Query || schemaType == p.schema.Mutation { 256 | if it, ok := p.tree.ResolverTree.Queries[schemaType.Name]; ok { 257 | return it.Return.GoType, nil 258 | } 259 | if it, ok := p.tree.ResolverTree.Mutations[schemaType.Name]; ok { 260 | return it.Return.GoType, nil 261 | } 262 | for _, field := range schemaType.Fields { 263 | lambdaDirective := field.Directives.ForName("lambda") 264 | 265 | if lambdaDirective == nil { 266 | continue 267 | } 268 | 269 | returnType := p.schema.Types[field.Type.Name()] 270 | returnGoType, err := p.parseType(returnType, false) 271 | if err != nil { 272 | return nil, err 273 | } 274 | returnField := &Return{ 275 | GoType: returnGoType, 276 | IsArray: graphql.IsArray(field.Type.String()), 277 | } 278 | 279 | var args []*Argument 280 | for _, arg := range field.Arguments { 281 | argType := p.schema.Types[arg.Type.Name()] 282 | argGoType, err := p.parseType(argType, false) 283 | if err != nil { 284 | return nil, err 285 | } 286 | 287 | args = append(args, &Argument{Name: arg.Name, 288 | GoType: argGoType, 289 | IsArray: graphql.IsArray(field.Type.String()), 290 | }) 291 | } 292 | out := middlewareRegex.FindAllStringSubmatch(field.Description, -1) 293 | 294 | var fieldMiddleware []string 295 | for _, i := range out { 296 | rawMiddleware := i[1] 297 | json.Unmarshal([]byte(rawMiddleware), &fieldMiddleware) 298 | } 299 | for _, m := range fieldMiddleware { 300 | p.tree.Middleware[m] = m 301 | } 302 | 303 | if schemaType == p.schema.Query { 304 | p.tree.ResolverTree.Queries[field.Name] = &Query{Name: field.Name, Description: field.Description, Arguments: args, Return: returnField, Middleware: fieldMiddleware} 305 | } 306 | 307 | if schemaType == p.schema.Mutation { 308 | p.tree.ResolverTree.Mutations[field.Name] = &Mutation{Name: field.Name, Description: field.Description, Arguments: args, Return: returnField, Middleware: fieldMiddleware} 309 | } 310 | } 311 | } else { 312 | // Model 313 | if it, ok := p.tree.ModelTree.Models[schemaType.Name]; ok { 314 | return it.GoType, nil 315 | } 316 | 317 | it := &Model{ 318 | Name: schemaType.Name, 319 | Description: schemaType.Description, 320 | GoType: goType, 321 | } 322 | 323 | p.tree.ModelTree.Models[it.Name] = it 324 | 325 | lambdaOnMutate := schemaType.Directives.ForName("lambdaOnMutate") 326 | if lambdaOnMutate != nil { 327 | if lambdaOnMutate.Arguments.ForName("add") != nil { 328 | it.LambdaOnMutate = append(it.LambdaOnMutate, ADD) 329 | } 330 | if lambdaOnMutate.Arguments.ForName("update") != nil { 331 | it.LambdaOnMutate = append(it.LambdaOnMutate, UPDATE) 332 | } 333 | if lambdaOnMutate.Arguments.ForName("delete") != nil { 334 | it.LambdaOnMutate = append(it.LambdaOnMutate, DELETE) 335 | } 336 | } 337 | 338 | for _, implementor := range p.schema.GetImplements(schemaType) { 339 | interfaceType, err := p.parseType(implementor, false) 340 | if err != nil { 341 | return nil, err 342 | } 343 | it.Implements = append(it.Implements, interfaceType) 344 | } 345 | 346 | for _, field := range schemaType.Fields { 347 | fieldType := p.schema.Types[field.Type.Name()] 348 | 349 | fieldGoType, err := p.parseType(fieldType, false) 350 | if err != nil { 351 | return nil, err 352 | } 353 | 354 | tag := `json:"` + field.Name + `"` 355 | if field.Name == "id" { 356 | tag += ` dql:"uid"` 357 | } else { 358 | tag += ` dql:"` + it.Name + "." + field.Name + `"` 359 | } 360 | 361 | modelField := &Field{ 362 | Name: field.Name, 363 | Description: field.Description, 364 | Tag: tag, 365 | GoType: fieldGoType, 366 | IsArray: graphql.IsArray(field.Type.String()), 367 | } 368 | it.Fields = append(it.Fields, modelField) 369 | 370 | lambdaDirective := field.Directives.ForName("lambda") 371 | 372 | if lambdaDirective != nil { 373 | out := middlewareRegex.FindAllStringSubmatch(field.Description, -1) 374 | 375 | var fieldMiddleware []string 376 | for _, i := range out { 377 | rawMiddleware := i[1] 378 | json.Unmarshal([]byte(rawMiddleware), &fieldMiddleware) 379 | } 380 | for _, m := range fieldMiddleware { 381 | p.tree.Middleware[m] = m 382 | } 383 | p.tree.ResolverTree.FieldResolvers[field.Name] = &FieldResolver{Field: modelField, Parent: &Parent{Name: schemaType.Name, GoType: it.GoType}, Middleware: fieldMiddleware} 384 | } 385 | } 386 | return it.GoType, nil 387 | } 388 | 389 | case ast.Enum: 390 | if it, ok := p.tree.ModelTree.Enums[schemaType.Name]; ok { 391 | return it.GoType, nil 392 | } 393 | it := &Enum{ 394 | Name: schemaType.Name, 395 | Description: schemaType.Description, 396 | GoType: goType, 397 | } 398 | 399 | for _, v := range schemaType.EnumValues { 400 | it.Values = append(it.Values, &EnumValue{ 401 | Name: v.Name, 402 | Description: v.Description, 403 | }) 404 | } 405 | 406 | p.tree.ModelTree.Enums[it.Name] = it 407 | return it.GoType, nil 408 | case ast.Scalar: 409 | if it, ok := p.tree.ModelTree.Scalars[schemaType.Name]; ok { 410 | return it.GoType, nil 411 | } 412 | it := &Scalar{ 413 | Name: schemaType.Name, 414 | Description: schemaType.Description, 415 | GoType: goType, 416 | } 417 | p.tree.ModelTree.Scalars[schemaType.Name] = it 418 | return it.GoType, nil 419 | } 420 | 421 | return nil, nil 422 | } 423 | 424 | func (p *Parser) hasLambda(def *ast.Definition) bool { 425 | 426 | for _, f := range p.force { 427 | if f == def.Name { 428 | return true 429 | } 430 | } 431 | if def.Directives.ForName("lambdaOnMutate") != nil { 432 | return true 433 | } 434 | for _, field := range def.Fields { 435 | if field.Directives.ForName("lambda") != nil { 436 | return true 437 | } 438 | } 439 | return false 440 | } 441 | -------------------------------------------------------------------------------- /codegen/rewriter/rewriter.go: -------------------------------------------------------------------------------- 1 | package rewriter 2 | 3 | import ( 4 | "go/ast" 5 | "path" 6 | "strings" 7 | 8 | "github.com/schartey/dgraph-lambda-go/codegen/config" 9 | "github.com/schartey/dgraph-lambda-go/codegen/parser" 10 | "github.com/schartey/dgraph-lambda-go/internal" 11 | ) 12 | 13 | type Rewriter struct { 14 | config *config.Config 15 | parsedTree *parser.Tree 16 | RewriteBodies map[string]string 17 | DeprecatedBodies map[string]string 18 | } 19 | 20 | func New(config *config.Config, parsedTree *parser.Tree) *Rewriter { 21 | rewriteBodies := make(map[string]string) 22 | deprecatedBodies := make(map[string]string) 23 | return &Rewriter{config: config, parsedTree: parsedTree, RewriteBodies: rewriteBodies, DeprecatedBodies: deprecatedBodies} 24 | } 25 | 26 | func (r *Rewriter) Load() error { 27 | r.RewriteBodies = make(map[string]string) 28 | r.DeprecatedBodies = make(map[string]string) 29 | 30 | pkgs := &internal.Packages{} 31 | // field resolvers 32 | if r.config.ResolverFilename == "resolver" { 33 | pkg, err := pkgs.Load(path.Join(r.config.Root, r.config.Resolver.Dir)) 34 | if err != nil { 35 | return err 36 | } 37 | for _, f := range pkg.Syntax { 38 | for _, d := range f.Decls { 39 | found := false 40 | 41 | d, isFunc := d.(*ast.FuncDecl) 42 | if !isFunc { 43 | continue 44 | } 45 | 46 | if strings.HasPrefix(d.Name.Name, "Query_") { 47 | queryName := strings.TrimPrefix(d.Name.Name, "Query_") 48 | 49 | for _, query := range r.parsedTree.ResolverTree.Queries { 50 | if query.Name == queryName { 51 | _, r.RewriteBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Body.Pos()+1, d.Body.End()-1) 52 | found = true 53 | break 54 | } 55 | } 56 | } 57 | 58 | if strings.HasPrefix(d.Name.Name, "Mutation_") { 59 | mutationName := strings.TrimPrefix(d.Name.Name, "Mutation_") 60 | 61 | for _, mutation := range r.parsedTree.ResolverTree.Mutations { 62 | if mutation.Name == mutationName { 63 | _, r.RewriteBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Body.Pos()+1, d.Body.End()-1) 64 | found = true 65 | break 66 | } 67 | } 68 | } 69 | 70 | if strings.HasPrefix(d.Name.Name, "Middleware_") { 71 | middlewareName := strings.TrimPrefix(d.Name.Name, "Middleware_") 72 | 73 | for _, middleware := range r.parsedTree.Middleware { 74 | if middleware == middlewareName { 75 | _, r.RewriteBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Body.Pos()+1, d.Body.End()-1) 76 | found = true 77 | break 78 | } 79 | } 80 | } 81 | 82 | if strings.HasPrefix(d.Name.Name, "Webhook_") { 83 | webhookName := strings.TrimPrefix(d.Name.Name, "Webhook_") 84 | 85 | for _, model := range r.parsedTree.ModelTree.Models { 86 | if model.TypeName.Name() == webhookName { 87 | _, r.RewriteBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Body.Pos()+1, d.Body.End()-1) 88 | found = true 89 | break 90 | } 91 | } 92 | } 93 | 94 | for _, fieldResolver := range r.parsedTree.ResolverTree.FieldResolvers { 95 | splitName := strings.Split(d.Name.Name, "_") 96 | 97 | if splitName[0] == fieldResolver.Parent.Name && splitName[1] == fieldResolver.Field.Name { 98 | _, r.RewriteBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Body.Pos()+1, d.Body.End()-1) 99 | found = true 100 | break 101 | } 102 | } 103 | 104 | if !found { 105 | _, r.DeprecatedBodies[d.Name.Name] = r.config.Packages.GetSource(pkg, d.Pos(), d.End()) 106 | } 107 | } 108 | } 109 | } 110 | return nil 111 | } 112 | -------------------------------------------------------------------------------- /dev.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.16 2 | 3 | WORKDIR /lambda 4 | 5 | COPY . . 6 | 7 | EXPOSE 8686 8 | 9 | RUN ["go", "get", "github.com/githubnemo/CompileDaemon"] 10 | 11 | #CMD [ "go", "build", "."] 12 | ENTRYPOINT CompileDaemon -log-prefix=false -build="go build ." -command="./dgraph-lambda-go run" -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.2" 2 | services: 3 | lambda: 4 | build: 5 | context: . 6 | dockerfile: dev.Dockerfile 7 | environment: 8 | DGRAPHQL_URL: http://alpha:8080 9 | DQL_URL: alpha:9080 10 | ports: 11 | - 8686:8686 12 | volumes: 13 | - .:/lambda 14 | networks: 15 | - dgraph 16 | 17 | networks: 18 | dgraph: 19 | external: true -------------------------------------------------------------------------------- /dson/dson.go: -------------------------------------------------------------------------------- 1 | package dson 2 | 3 | import jsoniter "github.com/json-iterator/go" 4 | 5 | var DqlJson = jsoniter.Config{ 6 | TagKey: "dql", 7 | }.Froze() 8 | 9 | func Marshal(v interface{}) ([]byte, error) { 10 | return DqlJson.Marshal(v) 11 | } 12 | 13 | func Unmarshal(data []byte, v interface{}) error { 14 | return DqlJson.Unmarshal(data, v) 15 | } 16 | -------------------------------------------------------------------------------- /examples/lambda/generated/generated.go: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "strings" 9 | 10 | "github.com/schartey/dgraph-lambda-go/api" 11 | "github.com/schartey/dgraph-lambda-go/examples/lambda/model" 12 | "github.com/schartey/dgraph-lambda-go/examples/lambda/resolvers" 13 | ) 14 | 15 | type Executer struct { 16 | api.ExecuterInterface 17 | fieldResolver resolvers.FieldResolver 18 | queryResolver resolvers.QueryResolver 19 | mutationResolver resolvers.MutationResolver 20 | middlewareResolver resolvers.MiddlewareResolver 21 | webhookResolver resolvers.WebhookResolver 22 | } 23 | 24 | func NewExecuter(resolver *resolvers.Resolver) api.ExecuterInterface { 25 | return Executer{fieldResolver: resolvers.FieldResolver{Resolver: resolver}, queryResolver: resolvers.QueryResolver{Resolver: resolver}, mutationResolver: resolvers.MutationResolver{Resolver: resolver}, middlewareResolver: resolvers.MiddlewareResolver{Resolver: resolver}, webhookResolver: resolvers.WebhookResolver{Resolver: resolver}} 26 | } 27 | 28 | func (e Executer) Resolve(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 29 | if request.Resolver == "$webhook" { 30 | return nil, e.resolveWebhook(ctx, request) 31 | } else { 32 | parentsBytes, underlyingError := request.Parents.MarshalJSON() 33 | if underlyingError != nil { 34 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 35 | } 36 | 37 | mc := &api.MiddlewareContext{Ctx: ctx, Request: request} 38 | if err = e.middleware(mc); err != nil { 39 | return nil, err 40 | } 41 | ctx = mc.Ctx 42 | request = mc.Request 43 | 44 | if strings.HasPrefix(request.Resolver, "Query.") { 45 | return e.resolveQuery(ctx, request) 46 | } else if strings.HasPrefix(request.Resolver, "Mutation.") { 47 | return e.resolveMutation(ctx, request) 48 | } else { 49 | return e.resolveField(ctx, request, parentsBytes) 50 | } 51 | } 52 | } 53 | 54 | func (e Executer) middleware(mc *api.MiddlewareContext) (err *api.LambdaError) { 55 | switch mc.Request.Resolver { 56 | case "User.active": 57 | { 58 | if err = e.middlewareResolver.Middleware_admin(mc); err != nil { 59 | return err 60 | } 61 | break 62 | } 63 | 64 | case "Query.getHotelByName": 65 | { 66 | if err = e.middlewareResolver.Middleware_user(mc); err != nil { 67 | return err 68 | } 69 | break 70 | } 71 | 72 | case "Query.getTopAuthors": 73 | { 74 | if err = e.middlewareResolver.Middleware_user(mc); err != nil { 75 | return err 76 | } 77 | if err = e.middlewareResolver.Middleware_admin(mc); err != nil { 78 | return err 79 | } 80 | break 81 | } 82 | 83 | case "Mutation.newAuthor": 84 | { 85 | if err = e.middlewareResolver.Middleware_admin(mc); err != nil { 86 | return err 87 | } 88 | break 89 | } 90 | 91 | } 92 | return nil 93 | } 94 | 95 | func (e Executer) resolveField(ctx context.Context, request *api.Request, parentsBytes []byte) (response []byte, err *api.LambdaError) { 96 | switch request.Resolver { 97 | case "User.active": 98 | { 99 | var parents []*model.User 100 | json.Unmarshal(parentsBytes, &parents) 101 | 102 | result, err := e.fieldResolver.User_active(ctx, parents, request.AuthHeader) 103 | if err != nil { 104 | return nil, err 105 | } 106 | 107 | var underlyingError error 108 | response, underlyingError = json.Marshal(result) 109 | if underlyingError != nil { 110 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 111 | } else { 112 | return response, nil 113 | } 114 | break 115 | } 116 | case "Post.additionalInfo": 117 | { 118 | var parents []*model.Post 119 | json.Unmarshal(parentsBytes, &parents) 120 | 121 | result, err := e.fieldResolver.Post_additionalInfo(ctx, parents, request.AuthHeader) 122 | if err != nil { 123 | return nil, err 124 | } 125 | 126 | var underlyingError error 127 | response, underlyingError = json.Marshal(result) 128 | if underlyingError != nil { 129 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 130 | } else { 131 | return response, nil 132 | } 133 | break 134 | } 135 | case "User.rank": 136 | { 137 | var parents []*model.User 138 | json.Unmarshal(parentsBytes, &parents) 139 | 140 | result, err := e.fieldResolver.User_rank(ctx, parents, request.AuthHeader) 141 | if err != nil { 142 | return nil, err 143 | } 144 | 145 | var underlyingError error 146 | response, underlyingError = json.Marshal(result) 147 | if underlyingError != nil { 148 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 149 | } else { 150 | return response, nil 151 | } 152 | break 153 | } 154 | case "User.reputation": 155 | { 156 | var parents []*model.User 157 | json.Unmarshal(parentsBytes, &parents) 158 | 159 | result, err := e.fieldResolver.User_reputation(ctx, parents, request.AuthHeader) 160 | if err != nil { 161 | return nil, err 162 | } 163 | 164 | var underlyingError error 165 | response, underlyingError = json.Marshal(result) 166 | if underlyingError != nil { 167 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 168 | } else { 169 | return response, nil 170 | } 171 | break 172 | } 173 | case "Figure.size": 174 | { 175 | var parents []*model.Figure 176 | json.Unmarshal(parentsBytes, &parents) 177 | 178 | result, err := e.fieldResolver.Figure_size(ctx, parents, request.AuthHeader) 179 | if err != nil { 180 | return nil, err 181 | } 182 | 183 | var underlyingError error 184 | response, underlyingError = json.Marshal(result) 185 | if underlyingError != nil { 186 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 187 | } else { 188 | return response, nil 189 | } 190 | break 191 | } 192 | } 193 | 194 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 195 | } 196 | 197 | func (e Executer) resolveQuery(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 198 | switch request.Resolver { 199 | case "Query.getApples": 200 | { 201 | result, err := e.queryResolver.Query_getApples(ctx, request.AuthHeader) 202 | if err != nil { 203 | return nil, err 204 | } 205 | 206 | var underlyingError error 207 | response, underlyingError = json.Marshal(result) 208 | if underlyingError != nil { 209 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 210 | } else { 211 | return response, nil 212 | } 213 | break 214 | } 215 | case "Query.getHotelByName": 216 | { 217 | var name string 218 | json.Unmarshal(request.Args["name"], &name) 219 | result, err := e.queryResolver.Query_getHotelByName(ctx, name, request.AuthHeader) 220 | if err != nil { 221 | return nil, err 222 | } 223 | 224 | var underlyingError error 225 | response, underlyingError = json.Marshal(result) 226 | if underlyingError != nil { 227 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 228 | } else { 229 | return response, nil 230 | } 231 | break 232 | } 233 | case "Query.getTopAuthors": 234 | { 235 | var id string 236 | json.Unmarshal(request.Args["id"], &id) 237 | result, err := e.queryResolver.Query_getTopAuthors(ctx, id, request.AuthHeader) 238 | if err != nil { 239 | return nil, err 240 | } 241 | 242 | var underlyingError error 243 | response, underlyingError = json.Marshal(result) 244 | if underlyingError != nil { 245 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 246 | } else { 247 | return response, nil 248 | } 249 | break 250 | } 251 | } 252 | 253 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 254 | } 255 | 256 | func (e Executer) resolveMutation(ctx context.Context, request *api.Request) (response []byte, err *api.LambdaError) { 257 | switch request.Resolver { 258 | case "Mutation.newAuthor": 259 | { 260 | var name string 261 | json.Unmarshal(request.Args["name"], &name) 262 | result, err := e.mutationResolver.Mutation_newAuthor(ctx, name, request.AuthHeader) 263 | if err != nil { 264 | return nil, err 265 | } 266 | 267 | var underlyingError error 268 | response, underlyingError = json.Marshal(result) 269 | if underlyingError != nil { 270 | return nil, &api.LambdaError{Underlying: underlyingError, Status: http.StatusInternalServerError} 271 | } else { 272 | return response, nil 273 | } 274 | break 275 | } 276 | } 277 | 278 | return nil, &api.LambdaError{Underlying: errors.New("could not find query resolver"), Status: http.StatusNotFound} 279 | } 280 | 281 | func (e Executer) resolveWebhook(ctx context.Context, request *api.Request) (err *api.LambdaError) { 282 | switch request.Event.TypeName { 283 | case "Hotel": 284 | err = e.webhookResolver.Webhook_Hotel(ctx, request.Event) 285 | return err 286 | case "CyclicType": 287 | err = e.webhookResolver.Webhook_CyclicType(ctx, request.Event) 288 | return err 289 | case "User": 290 | err = e.webhookResolver.Webhook_User(ctx, request.Event) 291 | return err 292 | } 293 | 294 | return &api.LambdaError{Underlying: errors.New("could not find webhook resolver"), Status: http.StatusNotFound} 295 | } 296 | -------------------------------------------------------------------------------- /examples/lambda/model/cyclic_model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type InverseType struct { 4 | Id string `json:"id" dql:"uid"` 5 | Name string `json:"name" dql:"InverseType.name"` 6 | CyclicType *CyclicType `json:"cyclicType" dql:"InverseType.cyclicType"` 7 | } 8 | -------------------------------------------------------------------------------- /examples/lambda/model/models_gen.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "strconv" 7 | "time" 8 | 9 | "github.com/schartey/dgraph-lambda-go/examples/models" 10 | "github.com/twpayne/go-geom" 11 | ) 12 | 13 | type Color interface { 14 | IsColor() 15 | } 16 | type Fruit interface { 17 | IsFruit() 18 | } 19 | type Post interface { 20 | IsPost() 21 | } 22 | type Shape interface { 23 | IsShape() 24 | } 25 | type Apple struct { 26 | Id string `json:"id" dql:"uid"` 27 | Price int64 `json:"price" dql:"Apple.price"` 28 | Color string `json:"color" dql:"Apple.color"` 29 | } 30 | type Author struct { 31 | Id string `json:"id" dql:"uid"` 32 | Name string `json:"name" dql:"Author.name"` 33 | Posts []*Post `json:"posts" dql:"Author.posts"` 34 | RecentlyLiked []*Post `json:"recentlyLiked" dql:"Author.recentlyLiked"` 35 | Friends []*Author `json:"friends" dql:"Author.friends"` 36 | } 37 | type CyclicType struct { 38 | Id string `json:"id" dql:"uid"` 39 | Name string `json:"name" dql:"CyclicType.name"` 40 | InverseType *InverseType `json:"inverseType" dql:"CyclicType.inverseType"` 41 | } 42 | type Figure struct { 43 | Id string `json:"id" dql:"uid"` 44 | Shape string `json:"shape" dql:"Figure.shape"` 45 | Color string `json:"color" dql:"Figure.color"` 46 | Size int64 `json:"size" dql:"Figure.size"` 47 | } 48 | type Hotel struct { 49 | Id string `json:"id" dql:"uid"` 50 | Name string `json:"name" dql:"Hotel.name"` 51 | Location *geom.T `json:"location" dql:"Hotel.location"` 52 | Area *geom.T `json:"area" dql:"Hotel.area"` 53 | } 54 | type PointList struct { 55 | Points []*geom.T `json:"points" dql:"PointList.points"` 56 | } 57 | type User struct { 58 | UserID string `json:"userID" dql:"User.userID"` 59 | Credentials *models.Credentials `json:"credentials" dql:"User.credentials"` 60 | Name string `json:"name" dql:"User.name"` 61 | LastSignIn *time.Time `json:"lastSignIn" dql:"User.lastSignIn"` 62 | RecentScores []float64 `json:"recentScores" dql:"User.recentScores"` 63 | Likes int64 `json:"likes" dql:"User.likes"` 64 | Reputation int64 `json:"reputation" dql:"User.reputation"` 65 | Rank int64 `json:"rank" dql:"User.rank"` 66 | Active bool `json:"active" dql:"User.active"` 67 | } 68 | 69 | type Tag string 70 | 71 | const ( 72 | TagGraphQL Tag = "GraphQL" 73 | TagDatabase Tag = "Database" 74 | TagQuestion Tag = "Question" 75 | ) 76 | 77 | var AllTag = []Tag{ 78 | TagGraphQL, 79 | TagDatabase, 80 | TagQuestion, 81 | } 82 | 83 | func (e Tag) IsValid() bool { 84 | switch e { 85 | case TagGraphQL, TagDatabase, TagQuestion: 86 | return true 87 | } 88 | return false 89 | } 90 | 91 | func (e Tag) String() string { 92 | return string(e) 93 | } 94 | 95 | func (e *Tag) UnmarshalGQL(v interface{}) error { 96 | str, ok := v.(string) 97 | if !ok { 98 | return fmt.Errorf("enums must be strings") 99 | } 100 | 101 | *e = Tag(str) 102 | if !e.IsValid() { 103 | return fmt.Errorf("%s is not a valid Tag", str) 104 | } 105 | return nil 106 | } 107 | 108 | func (e Tag) MarshalGQL(w io.Writer) { 109 | fmt.Fprint(w, strconv.Quote(e.String())) 110 | } 111 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/field.resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/schartey/dgraph-lambda-go/api" 7 | "github.com/schartey/dgraph-lambda-go/examples/lambda/model" 8 | ) 9 | 10 | type FieldResolverInterface interface { 11 | User_active(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]bool, *api.LambdaError) 12 | Post_additionalInfo(ctx context.Context, parents []*model.Post, authHeader api.AuthHeader) ([]string, *api.LambdaError) 13 | User_rank(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]int64, *api.LambdaError) 14 | User_reputation(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]int64, *api.LambdaError) 15 | Figure_size(ctx context.Context, parents []*model.Figure, authHeader api.AuthHeader) ([]int64, *api.LambdaError) 16 | } 17 | 18 | type FieldResolver struct { 19 | *Resolver 20 | } 21 | 22 | func (f *FieldResolver) User_active(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]bool, *api.LambdaError) { 23 | return nil, nil 24 | } 25 | 26 | func (f *FieldResolver) Post_additionalInfo(ctx context.Context, parents []*model.Post, authHeader api.AuthHeader) ([]string, *api.LambdaError) { 27 | return nil, nil 28 | } 29 | 30 | func (f *FieldResolver) User_rank(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]int64, *api.LambdaError) { 31 | return nil, nil 32 | } 33 | 34 | func (f *FieldResolver) User_reputation(ctx context.Context, parents []*model.User, authHeader api.AuthHeader) ([]int64, *api.LambdaError) { 35 | return nil, nil 36 | } 37 | 38 | func (f *FieldResolver) Figure_size(ctx context.Context, parents []*model.Figure, authHeader api.AuthHeader) ([]int64, *api.LambdaError) { 39 | return nil, nil 40 | } 41 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/middleware.resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | import ( 4 | "github.com/schartey/dgraph-lambda-go/api" 5 | ) 6 | 7 | type MiddlewareResolverInterface interface { 8 | Middleware_admin(mc *api.MiddlewareContext) *api.LambdaError 9 | Middleware_user(mc *api.MiddlewareContext) *api.LambdaError 10 | } 11 | 12 | type MiddlewareResolver struct { 13 | *Resolver 14 | } 15 | 16 | func (m *MiddlewareResolver) Middleware_admin(mc *api.MiddlewareContext) *api.LambdaError { 17 | return nil 18 | } 19 | 20 | func (m *MiddlewareResolver) Middleware_user(mc *api.MiddlewareContext) *api.LambdaError { 21 | return nil 22 | } 23 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/mutation.resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/schartey/dgraph-lambda-go/api" 7 | ) 8 | 9 | type MutationResolverInterface interface { 10 | Mutation_newAuthor(ctx context.Context, name string, authHeader api.AuthHeader) (string, *api.LambdaError) 11 | } 12 | 13 | type MutationResolver struct { 14 | *Resolver 15 | } 16 | 17 | func (q *MutationResolver) Mutation_newAuthor(ctx context.Context, name string, authHeader api.AuthHeader) (string, *api.LambdaError) { 18 | return "", nil 19 | } 20 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/query.resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/schartey/dgraph-lambda-go/api" 7 | "github.com/schartey/dgraph-lambda-go/examples/lambda/model" 8 | ) 9 | 10 | type QueryResolverInterface interface { 11 | Query_getApples(ctx context.Context, authHeader api.AuthHeader) ([]*model.Apple, *api.LambdaError) 12 | Query_getHotelByName(ctx context.Context, name string, authHeader api.AuthHeader) (*model.Hotel, *api.LambdaError) 13 | Query_getTopAuthors(ctx context.Context, id string, authHeader api.AuthHeader) ([]*model.Author, *api.LambdaError) 14 | } 15 | 16 | type QueryResolver struct { 17 | *Resolver 18 | } 19 | 20 | func (q *QueryResolver) Query_getApples(ctx context.Context, authHeader api.AuthHeader) ([]*model.Apple, *api.LambdaError) { 21 | return nil, nil 22 | } 23 | 24 | func (q *QueryResolver) Query_getHotelByName(ctx context.Context, name string, authHeader api.AuthHeader) (*model.Hotel, *api.LambdaError) { 25 | return nil, nil 26 | } 27 | 28 | func (q *QueryResolver) Query_getTopAuthors(ctx context.Context, id string, authHeader api.AuthHeader) ([]*model.Author, *api.LambdaError) { 29 | return nil, nil 30 | } 31 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | // Add objects to your desire 4 | type Resolver struct { 5 | } 6 | -------------------------------------------------------------------------------- /examples/lambda/resolvers/webhook.resolver.go: -------------------------------------------------------------------------------- 1 | package resolvers 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/schartey/dgraph-lambda-go/api" 7 | ) 8 | 9 | type WebhookResolverInterface interface { 10 | Webhook_CyclicType(ctx context.Context, event *api.Event) *api.LambdaError 11 | Webhook_Hotel(ctx context.Context, event *api.Event) *api.LambdaError 12 | Webhook_User(ctx context.Context, event *api.Event) *api.LambdaError 13 | } 14 | 15 | type WebhookResolver struct { 16 | *Resolver 17 | } 18 | 19 | func (w *WebhookResolver) Webhook_CyclicType(ctx context.Context, event *api.Event) *api.LambdaError { 20 | return nil 21 | } 22 | 23 | func (w *WebhookResolver) Webhook_Hotel(ctx context.Context, event *api.Event) *api.LambdaError { 24 | return nil 25 | } 26 | 27 | func (w *WebhookResolver) Webhook_User(ctx context.Context, event *api.Event) *api.LambdaError { 28 | return nil 29 | } 30 | -------------------------------------------------------------------------------- /examples/models/credentials.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "strconv" 7 | ) 8 | 9 | type Credentials struct { 10 | Id uint64 `json:"id"` 11 | FirebaseId string `json:"firebaseId"` 12 | Email string `json:"email"` 13 | PhoneNumber string `json:"phoneNumber"` 14 | } 15 | 16 | type EnumTest string 17 | 18 | const ( 19 | EnumTestASDF EnumTest = "ASDF" 20 | EnumTestFDAS EnumTest = "FDAS" 21 | ) 22 | 23 | var AllEnumTest = []EnumTest{ 24 | EnumTestASDF, 25 | EnumTestFDAS, 26 | } 27 | 28 | func (e EnumTest) IsValid() bool { 29 | switch e { 30 | case EnumTestASDF, EnumTestFDAS: 31 | return true 32 | } 33 | return false 34 | } 35 | 36 | func (e EnumTest) String() string { 37 | return string(e) 38 | } 39 | 40 | func (e *EnumTest) UnmarshalGQL(v interface{}) error { 41 | str, ok := v.(string) 42 | if !ok { 43 | return fmt.Errorf("enums must be strings") 44 | } 45 | 46 | *e = EnumTest(str) 47 | if !e.IsValid() { 48 | return fmt.Errorf("%s is not a valid EnumTest", str) 49 | } 50 | return nil 51 | } 52 | 53 | func (e EnumTest) MarshalGQL(w io.Writer) { 54 | fmt.Fprint(w, strconv.Quote(e.String())) 55 | } 56 | 57 | type T interface { 58 | IsT() 59 | } 60 | -------------------------------------------------------------------------------- /examples/server.go: -------------------------------------------------------------------------------- 1 | package examples 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "sync" 10 | "time" 11 | 12 | "github.com/go-chi/chi" 13 | "github.com/schartey/dgraph-lambda-go/api" 14 | "github.com/schartey/dgraph-lambda-go/examples/lambda/generated" 15 | "github.com/schartey/dgraph-lambda-go/examples/lambda/resolvers" 16 | ) 17 | 18 | func RunWithServer() { 19 | c := make(chan os.Signal, 1) 20 | signal.Notify(c, os.Interrupt) 21 | 22 | wg := &sync.WaitGroup{} 23 | wg.Add(1) 24 | 25 | resolver := &resolvers.Resolver{} 26 | executer := generated.NewExecuter(resolver) 27 | lambda := api.New(executer) 28 | srv, err := lambda.Serve(wg) 29 | if err != nil { 30 | fmt.Println(err) 31 | } 32 | <-c 33 | fmt.Println("Shutdown request (Ctrl-C) caught.") 34 | fmt.Println("Shutting down...") 35 | 36 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 37 | defer cancel() 38 | 39 | if err := srv.Shutdown(ctx); err != nil { 40 | fmt.Println(err) 41 | } 42 | wg.Wait() 43 | } 44 | 45 | func RunWithRoute() { 46 | r := chi.NewRouter() 47 | 48 | resolver := &resolvers.Resolver{} 49 | executer := generated.NewExecuter(resolver) 50 | lambda := api.New(executer) 51 | 52 | r.Post("/graphql-worker", lambda.Route) 53 | 54 | fmt.Println("Lambda listening on 8686") 55 | fmt.Println(http.ListenAndServe(":8686", r)) 56 | } 57 | -------------------------------------------------------------------------------- /examples/test.graphql: -------------------------------------------------------------------------------- 1 | type Credentials { 2 | id: ID! 3 | firebaseId: String! 4 | } 5 | 6 | type User @lambdaOnMutate(add: true, update: true, delete: true) { 7 | userID: ID! 8 | credentials: Credentials! 9 | name: String! 10 | lastSignIn: DateTime @search(by: [year]) 11 | """ 12 | @middleware(["ignored"]) 13 | """ 14 | recentScores: [Float] 15 | likes: Int @deprecated(reason: "Use Reputation instead") 16 | reputation: Int @lambda 17 | rank: Int @lambda 18 | """ 19 | @middleware(["admin"]) 20 | """ 21 | active: Boolean @lambda 22 | } 23 | 24 | enum Tag { 25 | GraphQL 26 | Database 27 | Question 28 | } 29 | 30 | interface Post { 31 | id: ID! 32 | title: String! 33 | text: String 34 | datePublished: DateTime 35 | tags: [Tag!]! 36 | author: Author! 37 | additionalInfo: String @lambda 38 | } 39 | 40 | type Author @secret(field: "pwd") { 41 | id: ID! 42 | name: String! 43 | posts: [Post] @hasInverse(field: author) 44 | recentlyLiked: [Post] 45 | friends: [Author] 46 | } 47 | 48 | interface Fruit { 49 | id: ID! 50 | price: Int! 51 | } 52 | 53 | type Apple implements Fruit { 54 | id: ID! 55 | price: Int! 56 | color: String! 57 | } 58 | 59 | type Banana implements Fruit { 60 | id: ID! 61 | price: Int! 62 | } 63 | 64 | input AppleInput { 65 | price: Int! 66 | color: String! 67 | } 68 | 69 | input BananaInput { 70 | price: Int! 71 | } 72 | 73 | type Question implements Post { 74 | id: ID! 75 | title: String! 76 | text: String 77 | datePublished: DateTime 78 | tags: [Tag!]! 79 | author: Author! 80 | additionalInfo: String 81 | } 82 | 83 | type Comment implements Post { 84 | id: ID! 85 | title: String! 86 | text: String 87 | datePublished: DateTime 88 | commentsOn: Post! 89 | tags: [Tag!]! 90 | author: Author! 91 | additionalInfo: String 92 | } 93 | 94 | interface Shape { 95 | id: ID! 96 | shape: String! 97 | } 98 | 99 | interface Color { 100 | id: ID! 101 | color: String! 102 | } 103 | 104 | type Figure implements Shape & Color @generate( 105 | query: { 106 | get: false, 107 | query: true, 108 | aggregate: false 109 | }, 110 | mutation: { 111 | add: true, 112 | delete: false 113 | }, 114 | subscription: false 115 | ) { 116 | id: ID! 117 | shape: String! 118 | color: String! 119 | size: Int! @lambda 120 | } 121 | 122 | enum Category { 123 | Fish 124 | Amphibian 125 | Reptile 126 | Bird 127 | Mammal 128 | InVertebrate 129 | } 130 | 131 | interface Animal { 132 | id: ID! 133 | category: Category @search 134 | } 135 | 136 | type Dog implements Animal { 137 | id: ID! 138 | breed: String @search 139 | category: Category @search 140 | } 141 | 142 | type Parrot implements Animal { 143 | id: ID! 144 | repeatsWords: [String] 145 | category: Category @search 146 | } 147 | 148 | type Cheetah implements Animal { 149 | id: ID! 150 | speed: Float 151 | category: Category @search 152 | } 153 | 154 | type Human { 155 | name: String! 156 | pets: [Animal!]! 157 | } 158 | 159 | union HomeMember = Dog | Parrot | Human 160 | 161 | type Zoo { 162 | id: ID! 163 | animals: [Animal] 164 | city: String 165 | } 166 | 167 | type Home { 168 | id: ID! 169 | address: String 170 | members: [HomeMember] 171 | } 172 | 173 | type Hotel @lambdaOnMutate(add: true, update: true, delete: true) { 174 | id: String! @id 175 | name: String! 176 | location: Point 177 | area: Polygon 178 | } 179 | 180 | type CyclicType @lambdaOnMutate(add: true, update: true, delete: true) { 181 | id: ID! 182 | name: String! 183 | inverseType: InverseType! 184 | } 185 | 186 | type InverseType { 187 | id: ID! 188 | name: String! 189 | cyclicType: CyclicType! @hasInverse(field: inverseType) 190 | } 191 | 192 | type Query { 193 | getApples: [Apple] @lambda 194 | """ 195 | @middleware(["user", "admin"]) 196 | """ 197 | getTopAuthors(id: ID!): [Author] @lambda 198 | """ 199 | @middleware(["user"]) 200 | """ 201 | getHotelByName(name: String!): Hotel @lambda 202 | } 203 | 204 | type Mutation { 205 | """ 206 | @middleware(["admin"]) 207 | """ 208 | newAuthor(name: String!): ID! @lambda 209 | } -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/schartey/dgraph-lambda-go 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/agnivade/levenshtein v1.1.1 // indirect 7 | github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect 8 | github.com/go-chi/chi v4.1.2+incompatible 9 | github.com/json-iterator/go v1.1.12 10 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 11 | github.com/pkg/errors v0.9.1 12 | github.com/stretchr/objx v0.3.0 // indirect 13 | github.com/stretchr/testify v1.7.0 14 | github.com/twpayne/go-geom v1.4.1 15 | github.com/urfave/cli/v2 v2.3.0 16 | github.com/vektah/gqlparser/v2 v2.2.0 17 | golang.org/x/mod v0.5.1 18 | golang.org/x/net v0.0.0-20211108170745-6635138e15ea // indirect 19 | golang.org/x/sys v0.0.0-20211107104306-e0b2ad06fe42 // indirect 20 | golang.org/x/tools v0.1.7 21 | gopkg.in/yaml.v2 v2.4.0 22 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect 23 | ) 24 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/DATA-DOG/go-sqlmock v1.3.2/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= 4 | github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= 5 | github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= 6 | github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= 7 | github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= 8 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= 9 | github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= 10 | github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= 11 | github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= 12 | github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= 13 | github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= 14 | github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= 15 | github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= 16 | github.com/cenkalti/backoff/v3 v3.0.0/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs= 17 | github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= 18 | github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= 19 | github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= 20 | github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 21 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 22 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 23 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 24 | github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= 25 | github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= 26 | github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= 27 | github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= 28 | github.com/go-chi/chi v4.1.2+incompatible h1:fGFk2Gmi/YKXk0OmGfBh0WgmN3XB8lVnEyNz34tQRec= 29 | github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= 30 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 31 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 32 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 33 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 34 | github.com/huandu/xstrings v1.3.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= 35 | github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= 36 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 37 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 38 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 39 | github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 40 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 41 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 42 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 43 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 44 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 45 | github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 46 | github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= 47 | github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= 48 | github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= 49 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 50 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 51 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 52 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 53 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 54 | github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= 55 | github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= 56 | github.com/opencontainers/runc v1.0.0-rc9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= 57 | github.com/ory/dockertest/v3 v3.6.0/go.mod h1:4ZOpj8qBUmh8fcBSVzkH2bws2s91JdGvHUqan4GHEuQ= 58 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 59 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 60 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 61 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 62 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 63 | github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 64 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 65 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 66 | github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= 67 | github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= 68 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= 69 | github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= 70 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 71 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 72 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 73 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 74 | github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= 75 | github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= 76 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 77 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 78 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 79 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 80 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 81 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 82 | github.com/twpayne/go-geom v1.4.1 h1:LeivFqaGBRfyg0XJJ9pkudcptwhSSrYN9KZUW6HcgdA= 83 | github.com/twpayne/go-geom v1.4.1/go.mod h1:k/zktXdL+qnA6OgKsdEGUTA17jbQ2ZPTUa3CCySuGpE= 84 | github.com/twpayne/go-kml v1.5.2/go.mod h1:kz8jAiIz6FIdU2Zjce9qGlVtgFYES9vt7BTPBHf5jl4= 85 | github.com/twpayne/go-polyline v1.0.0/go.mod h1:ICh24bcLYBX8CknfvNPKqoTbe+eg+MX1NPyJmSBo7pU= 86 | github.com/twpayne/go-waypoint v0.0.0-20200706203930-b263a7f6e4e8/go.mod h1:qj5pHncxKhu9gxtZEYWypA/z097sxhFlbTyOyt9gcnU= 87 | github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= 88 | github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= 89 | github.com/vektah/gqlparser/v2 v2.2.0 h1:bAc3slekAAJW6sZTi07aGq0OrfaCjj4jxARAaC7g2EM= 90 | github.com/vektah/gqlparser/v2 v2.2.0/go.mod h1:i3mQIGIrbK2PD1RrCeMTlVbkF2FJ6WkU1KJlJlC+3F4= 91 | github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 92 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 93 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 94 | golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 95 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 96 | golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38= 97 | golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= 98 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 99 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 100 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 101 | golang.org/x/net v0.0.0-20191003171128-d98b1b443823/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 102 | golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 103 | golang.org/x/net v0.0.0-20211108170745-6635138e15ea h1:FosBMXtOc8Tp9Hbo4ltl1WJSrTVewZU8MPnTPY2HdH8= 104 | golang.org/x/net v0.0.0-20211108170745-6635138e15ea/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 105 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 106 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 107 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 108 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 109 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 110 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 111 | golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 112 | golang.org/x/sys v0.0.0-20200121082415-34d275377bf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 113 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 114 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 115 | golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 116 | golang.org/x/sys v0.0.0-20211107104306-e0b2ad06fe42 h1:G2DDmludOQZoWbpCr7OKDxnl478ZBGMcOhrv+ooX/Q4= 117 | golang.org/x/sys v0.0.0-20211107104306-e0b2ad06fe42/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 118 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 119 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 120 | golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= 121 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 122 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 123 | golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 124 | golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= 125 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 126 | golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= 127 | golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= 128 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 129 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 130 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 131 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 132 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 133 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 134 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 135 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 136 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 137 | gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 138 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 139 | gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 140 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 141 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 142 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 143 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= 144 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 145 | gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= 146 | -------------------------------------------------------------------------------- /internal/mod.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "errors" 5 | "go/build" 6 | "os" 7 | "os/exec" 8 | "path/filepath" 9 | 10 | "golang.org/x/mod/modfile" 11 | ) 12 | 13 | func findGoModFile(root string, maxDepth int) (string, error) { 14 | if root == "/" || maxDepth == 0 { 15 | return "", errors.New("could not find go.mod file") 16 | } 17 | var files []string 18 | 19 | err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { 20 | files = append(files, path) 21 | return nil 22 | }) 23 | if err != nil { 24 | return "", err 25 | } 26 | for _, file := range files { 27 | if filepath.Base(file) == "go.mod" { 28 | return root, nil 29 | } 30 | } 31 | return findGoModFile(filepath.Dir(root), maxDepth-1) 32 | } 33 | 34 | func GetModuleName() (string, error) { 35 | 36 | root, err := filepath.Abs(".") 37 | if err != nil { 38 | return "", err 39 | } 40 | 41 | root, err = findGoModFile(root, 3) 42 | if err != nil { 43 | return "", err 44 | } 45 | 46 | data, err := os.ReadFile(filepath.Join(root, "go.mod")) 47 | if err != nil { 48 | return "", err 49 | } 50 | file, err := modfile.Parse("go.mod", data, nil) 51 | if err != nil { 52 | return "", err 53 | } 54 | 55 | return file.Module.Mod.Path, nil 56 | } 57 | 58 | func Tidy() error { 59 | cmd := exec.Command("go", "mod", "tidy") 60 | if err := cmd.Run(); err != nil { 61 | return err 62 | } 63 | return nil 64 | } 65 | 66 | func FixImports() error { 67 | gopath := os.Getenv("GOPATH") 68 | if gopath == "" { 69 | gopath = build.Default.GOPATH 70 | } 71 | cmd := exec.Command(filepath.Join(gopath, "bin", "goimports"), "-w", ".") 72 | if err := cmd.Run(); err != nil { 73 | return err 74 | } 75 | return nil 76 | } 77 | -------------------------------------------------------------------------------- /internal/mod_test.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "path/filepath" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func Test_findGoModFile_Fail(t *testing.T) { 11 | root, err := filepath.Abs(".") 12 | assert.NoError(t, err) 13 | 14 | _, err = findGoModFile(root, 1) 15 | assert.Error(t, err, "could not find go.mod file") 16 | } 17 | 18 | func Test_findGoModFile_Success(t *testing.T) { 19 | root, err := filepath.Abs(".") 20 | assert.NoError(t, err) 21 | 22 | path, err := findGoModFile(root, 2) 23 | 24 | assert.NoError(t, err) 25 | assert.Contains(t, path, "dgraph-lambda-go") 26 | 27 | root, err = filepath.Abs(".") 28 | assert.NoError(t, err) 29 | 30 | path, err = findGoModFile(root, 3) 31 | 32 | assert.NoError(t, err) 33 | assert.Contains(t, path, "dgraph-lambda-go") 34 | } 35 | 36 | func Test_GetModuleName(t *testing.T) { 37 | moduleName, err := GetModuleName() 38 | assert.NoError(t, err) 39 | 40 | assert.Equal(t, "github.com/schartey/dgraph-lambda-go", moduleName) 41 | } 42 | -------------------------------------------------------------------------------- /internal/packages.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "go/ast" 7 | "go/token" 8 | "io/ioutil" 9 | "strings" 10 | 11 | "golang.org/x/tools/go/packages" 12 | ) 13 | 14 | var mode = packages.NeedName | 15 | packages.NeedFiles | 16 | packages.NeedImports | 17 | packages.NeedTypes | 18 | packages.NeedSyntax | 19 | packages.NeedTypesInfo 20 | 21 | type Packages struct { 22 | packages map[string]*packages.Package 23 | files map[string]string 24 | } 25 | 26 | func (p *Packages) Load(importPath string) (*packages.Package, error) { 27 | if p.packages == nil { 28 | p.packages = map[string]*packages.Package{} 29 | } 30 | if p.files == nil { 31 | p.files = map[string]string{} 32 | } 33 | pkgs, err := packages.Load(&packages.Config{Mode: mode}, importPath) 34 | if err != nil { 35 | return nil, err 36 | } 37 | 38 | for _, pkg := range pkgs { 39 | if len(pkg.Errors) != 0 { 40 | return nil, pkg.Errors[0] 41 | } 42 | p.packages[importPath] = pkg 43 | } 44 | 45 | return p.packages[importPath], nil 46 | } 47 | 48 | func (p *Packages) PackageFromPath(importPath string) (*packages.Package, error) { 49 | 50 | if pkg, found := p.packages[importPath]; !found { 51 | return nil, errors.New("package not found") 52 | } else { 53 | return pkg, nil 54 | } 55 | } 56 | 57 | func (p *Packages) GetFileNameType(importPath string, t string) (string, error) { 58 | if pkg, err := p.PackageFromPath(importPath); err != nil { 59 | return "", err 60 | } else { 61 | for _, f := range pkg.Syntax { 62 | for _, d := range f.Decls { 63 | d, isDecl := d.(*ast.GenDecl) 64 | if !isDecl { 65 | continue 66 | } 67 | 68 | fileName, body := p.GetSource(pkg, d.Pos(), d.End()) 69 | if strings.Contains(body, "type "+t) { 70 | return fileName, nil 71 | } 72 | } 73 | } 74 | return "", errors.New("not found") 75 | } 76 | } 77 | 78 | func (p *Packages) GetSource(pkg *packages.Package, start, end token.Pos) (string, string) { 79 | startPos := pkg.Fset.Position(start) 80 | endPos := pkg.Fset.Position(end) 81 | 82 | if startPos.Filename != endPos.Filename { 83 | panic("cant get source spanning multiple files") 84 | } 85 | 86 | file := p.getFile(startPos.Filename) 87 | return startPos.Filename, file[startPos.Offset:endPos.Offset] 88 | } 89 | 90 | func (p *Packages) getFile(filename string) string { 91 | 92 | if file, ok := p.files[filename]; !ok { 93 | b, err := ioutil.ReadFile(filename) 94 | if err != nil { 95 | panic(fmt.Errorf("unable to load file, already exists: %s", err.Error())) 96 | } 97 | p.files[filename] = string(b) 98 | return p.files[filename] 99 | } else { 100 | return file 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /internal/packages_test.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_Packages(t *testing.T) { 10 | packages := &Packages{} 11 | 12 | pkg, err := packages.Load("github.com/schartey/dgraph-lambda-go/internal") 13 | assert.NoError(t, err) 14 | assert.Equal(t, "internal", pkg.Name) 15 | assert.Equal(t, "github.com/schartey/dgraph-lambda-go/internal", pkg.PkgPath) 16 | 17 | cached, err := packages.PackageFromPath("github.com/schartey/dgraph-lambda-go/internal") 18 | assert.NoError(t, err) 19 | assert.Equal(t, pkg, cached) 20 | } 21 | 22 | func Test_Packages_Fail(t *testing.T) { 23 | packages := &Packages{} 24 | 25 | _, err := packages.Load("invalid/package") 26 | assert.Error(t, err) 27 | 28 | _, err = packages.PackageFromPath("invalid/package") 29 | assert.Error(t, err) 30 | } 31 | -------------------------------------------------------------------------------- /lambda.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | filename: examples/lambda/generated/generated.go 6 | package: generated 7 | 8 | model: 9 | filename: examples/lambda/model/models_gen.go 10 | package: model 11 | 12 | autobind: 13 | - "github.com/schartey/dgraph-lambda-go/examples/models" 14 | 15 | resolver: 16 | layout: follow-schema 17 | dir: examples/lambda/resolvers 18 | package: resolvers 19 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 20 | 21 | server: 22 | standalone: true -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/schartey/dgraph-lambda-go/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /test_resources/faulty1.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | package: generated 6 | 7 | model: 8 | filename: examples/lambda/model/models_gen.go 9 | package: model 10 | 11 | autobind: 12 | - "github.com/schartey/dgraph-lambda-go/examples/models" 13 | 14 | resolver: 15 | layout: follow-schema 16 | dir: examples/lambda/resolvers 17 | package: resolvers 18 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 19 | 20 | server: 21 | standalone: true -------------------------------------------------------------------------------- /test_resources/faulty2.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | filename: examples/lambda/generated/generated.go 6 | 7 | model: 8 | filename: examples/lambda/model/models_gen.go 9 | package: model 10 | 11 | autobind: 12 | - "github.com/schartey/dgraph-lambda-go/examples/models" 13 | 14 | resolver: 15 | layout: follow-schema 16 | dir: examples/lambda/resolvers 17 | package: resolvers 18 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 19 | 20 | server: 21 | standalone: true -------------------------------------------------------------------------------- /test_resources/faulty3.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | filename: examples/lambda/generated/generated.go 6 | package: generated 7 | 8 | model: 9 | package: model 10 | 11 | autobind: 12 | - "github.com/schartey/dgraph-lambda-go/examples/models" 13 | 14 | resolver: 15 | layout: follow-schema 16 | dir: examples/lambda/resolvers 17 | package: resolvers 18 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 19 | 20 | server: 21 | standalone: true -------------------------------------------------------------------------------- /test_resources/faulty4.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | filename: examples/lambda/generated/generated.go 6 | package: generated 7 | 8 | model: 9 | filename: examples/lambda/model/models_gen.go 10 | 11 | autobind: 12 | - "github.com/schartey/dgraph-lambda-go/examples/models" 13 | 14 | resolver: 15 | layout: follow-schema 16 | dir: examples/lambda/resolvers 17 | package: resolvers 18 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 19 | 20 | server: 21 | standalone: true -------------------------------------------------------------------------------- /test_resources/faulty5.yaml: -------------------------------------------------------------------------------- 1 | schema: 2 | - ./examples/*.graphql 3 | 4 | exec: 5 | package: generated 6 | 7 | model: 8 | filename: examples/lambda/model/models_gen.go 9 | package: model 10 | 11 | autobind: 12 | - "github.com/schartey/dgraph-lambda-go/examples/models" 13 | 14 | resolver: 15 | layout: follow-schema 16 | package: resolvers 17 | filename_template: "{resolver}.resolver.go" # should also allow "{name}.resolvers.go" 18 | 19 | server: 20 | standalone: true --------------------------------------------------------------------------------