From 9cfb56f123898a888c210a89d34a651ce1f4d0a5 Mon Sep 17 00:00:00 2001 From: Tobe O Date: Mon, 29 Apr 2019 13:12:23 -0400 Subject: [PATCH] Complete todo api --- lib/src/models/todo.dart | 11 ++ lib/src/models/todo.g.dart | 157 ++++++++++++++++++++++++++++ lib/src/routes/graphql/graphql.dart | 20 ++++ lib/src/routes/graphql/schema.dart | 22 ++++ lib/src/routes/graphql/todo.dart | 73 +++++++++++++ lib/src/routes/routes.dart | 4 + pubspec.yaml | 4 + 7 files changed, 291 insertions(+) create mode 100644 lib/src/models/todo.dart create mode 100644 lib/src/models/todo.g.dart create mode 100644 lib/src/routes/graphql/graphql.dart create mode 100644 lib/src/routes/graphql/schema.dart create mode 100644 lib/src/routes/graphql/todo.dart diff --git a/lib/src/models/todo.dart b/lib/src/models/todo.dart new file mode 100644 index 0000000..6c9bf89 --- /dev/null +++ b/lib/src/models/todo.dart @@ -0,0 +1,11 @@ +import 'package:angel_serialize/angel_serialize.dart'; +import 'package:graphql_schema/graphql_schema.dart'; +part 'todo.g.dart'; + +@graphQLClass +@serializable +abstract class _Todo extends Model { + String get text; + + bool get isComplete; +} diff --git a/lib/src/models/todo.g.dart b/lib/src/models/todo.g.dart new file mode 100644 index 0000000..274580a --- /dev/null +++ b/lib/src/models/todo.g.dart @@ -0,0 +1,157 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'todo.dart'; + +// ************************************************************************** +// JsonModelGenerator +// ************************************************************************** + +@generatedSerializable +class Todo extends _Todo { + Todo({this.id, this.text, this.isComplete, this.createdAt, this.updatedAt}); + + @override + final String id; + + @override + final String text; + + @override + final bool isComplete; + + @override + final DateTime createdAt; + + @override + final DateTime updatedAt; + + Todo copyWith( + {String id, + String text, + bool isComplete, + DateTime createdAt, + DateTime updatedAt}) { + return new Todo( + id: id ?? this.id, + text: text ?? this.text, + isComplete: isComplete ?? this.isComplete, + createdAt: createdAt ?? this.createdAt, + updatedAt: updatedAt ?? this.updatedAt); + } + + bool operator ==(other) { + return other is _Todo && + other.id == id && + other.text == text && + other.isComplete == isComplete && + other.createdAt == createdAt && + other.updatedAt == updatedAt; + } + + @override + int get hashCode { + return hashObjects([id, text, isComplete, createdAt, updatedAt]); + } + + @override + String toString() { + return "Todo(id=$id, text=$text, isComplete=$isComplete, createdAt=$createdAt, updatedAt=$updatedAt)"; + } + + Map toJson() { + return TodoSerializer.toMap(this); + } +} + +// ************************************************************************** +// SerializerGenerator +// ************************************************************************** + +const TodoSerializer todoSerializer = const TodoSerializer(); + +class TodoEncoder extends Converter { + const TodoEncoder(); + + @override + Map convert(Todo model) => TodoSerializer.toMap(model); +} + +class TodoDecoder extends Converter { + const TodoDecoder(); + + @override + Todo convert(Map map) => TodoSerializer.fromMap(map); +} + +class TodoSerializer extends Codec { + const TodoSerializer(); + + @override + get encoder => const TodoEncoder(); + @override + get decoder => const TodoDecoder(); + static Todo fromMap(Map map) { + return new Todo( + id: map['id'] as String, + text: map['text'] as String, + isComplete: map['is_complete'] as bool, + createdAt: map['created_at'] != null + ? (map['created_at'] is DateTime + ? (map['created_at'] as DateTime) + : DateTime.parse(map['created_at'].toString())) + : null, + updatedAt: map['updated_at'] != null + ? (map['updated_at'] is DateTime + ? (map['updated_at'] as DateTime) + : DateTime.parse(map['updated_at'].toString())) + : null); + } + + static Map toMap(_Todo model) { + if (model == null) { + return null; + } + return { + 'id': model.id, + 'text': model.text, + 'is_complete': model.isComplete, + 'created_at': model.createdAt?.toIso8601String(), + 'updated_at': model.updatedAt?.toIso8601String() + }; + } +} + +abstract class TodoFields { + static const List allFields = [ + id, + text, + isComplete, + createdAt, + updatedAt + ]; + + static const String id = 'id'; + + static const String text = 'text'; + + static const String isComplete = 'is_complete'; + + static const String createdAt = 'created_at'; + + static const String updatedAt = 'updated_at'; +} + +// ************************************************************************** +// _GraphQLGenerator +// ************************************************************************** + +/// Auto-generated from [Todo]. +final GraphQLObjectType todoGraphQLType = + objectType('Todo', isInterface: false, interfaces: [], fields: [ + field('id', graphQLString), + field('text', graphQLString), + field('is_complete', graphQLBoolean), + field('created_at', graphQLDate), + field('updated_at', graphQLDate), + field('idAsInt', graphQLInt) +]); diff --git a/lib/src/routes/graphql/graphql.dart b/lib/src/routes/graphql/graphql.dart new file mode 100644 index 0000000..2c6a7d1 --- /dev/null +++ b/lib/src/routes/graphql/graphql.dart @@ -0,0 +1,20 @@ +import 'package:angel_framework/angel_framework.dart'; +import 'package:angel_graphql/angel_graphql.dart'; +import 'package:graphql_server/graphql_server.dart'; +import 'schema.dart'; + +/// Configures the [app] to server GraphQL. +void configureServer(Angel app) { + // Create a [GraphQL] service instance, using our schema. + var schema = createSchema(app); + var graphQL = GraphQL(schema); + + // Mount a handler that responds to GraphQL queries. + app.all('/graphql', graphQLHttp(graphQL)); + + // In development, serve the GraphiQL IDE/editor. + // More info: https://github.com/graphql/graphiql + if (!app.environment.isProduction) { + app.get('/graphiql', graphiQL()); + } +} diff --git a/lib/src/routes/graphql/schema.dart b/lib/src/routes/graphql/schema.dart new file mode 100644 index 0000000..b0b2742 --- /dev/null +++ b/lib/src/routes/graphql/schema.dart @@ -0,0 +1,22 @@ +import 'package:angel_framework/angel_framework.dart'; +import 'package:graphql_schema/graphql_schema.dart'; +import 'todo.dart'; + +/// Creates a GraphQL schema that manages an in-memory store of +/// Todo items. +GraphQLSchema createSchema(Angel app) { + var queryType = objectType( + 'TodoQuery', + fields: todoQueryFields(app), + ); + + var mutationType = objectType( + 'TodoMutation', + fields: todoQueryFields(app), + ); + + return graphQLSchema( + queryType: queryType, + mutationType: mutationType, + ); +} diff --git a/lib/src/routes/graphql/todo.dart b/lib/src/routes/graphql/todo.dart new file mode 100644 index 0000000..54c99fd --- /dev/null +++ b/lib/src/routes/graphql/todo.dart @@ -0,0 +1,73 @@ +import 'package:angel/src/models/todo.dart'; +import 'package:angel_framework/angel_framework.dart'; +import 'package:angel_graphql/angel_graphql.dart'; +import 'package:graphql_schema/graphql_schema.dart'; + +/// Find or create an in-memory Todo store. +MapService _getTodoService(Angel app) { + const key = 'todoService'; + + // If there is already an existing singleton, return it. + if (app.container.hasNamed(key)) { + return app.container.findByName(key); + } + + // Create an in-memory service. We will use this + // as the backend to store Todo objects, serialized to Maps. + var mapService = MapService(); + + // Register this service as a named singleton in the app container, + // so that we do not inadvertently create another instance. + app.container.registerNamedSingleton(key, mapService); + + return mapService; +} + +/// Returns fields to be inserted into the query type. +Iterable todoQueryFields(Angel app) { + var todoService = _getTodoService(app); + + // Here, we use special resolvers to read data from our store. + return [ + field( + 'todos', + listOf(todoGraphQLType), + resolve: resolveViaServiceIndex(todoService), + ), + field( + 'todo', + todoGraphQLType, + resolve: resolveViaServiceRead(todoService), + inputs: [ + GraphQLFieldInput('id', graphQLString.nonNullable()), + ], + ), + ]; +} + +/// Returns fields to be inserted into the query type. +Iterable todoMutationFields(Angel app) { + var todoService = _getTodoService(app); + var todoInputType = todoGraphQLType.toInputObject('TodoInput'); + + // This time, we use resolvers to modify the data in the store. + return [ + field( + 'createTodo', + todoGraphQLType, + resolve: resolveViaServiceCreate(todoService), + inputs: [ + GraphQLFieldInput('data', todoInputType.nonNullable()), + ], + ), + field( + 'modifyTodo', + todoGraphQLType, + resolve: resolveViaServiceModify(todoService), + inputs: [ + GraphQLFieldInput('id', graphQLString.nonNullable()), + GraphQLFieldInput('data', todoInputType.nonNullable()), + ], + ), + ]; +} diff --git a/lib/src/routes/routes.dart b/lib/src/routes/routes.dart index 9396211..762b200 100644 --- a/lib/src/routes/routes.dart +++ b/lib/src/routes/routes.dart @@ -5,6 +5,7 @@ import 'package:angel_framework/angel_framework.dart'; import 'package:angel_static/angel_static.dart'; import 'package:file/file.dart'; import 'controllers/controllers.dart' as controllers; +import 'graphql/graphql.dart' as graphql; /// Put your app routes here! /// @@ -16,6 +17,9 @@ AngelConfigurer configureServer(FileSystem fileSystem) { // Typically, you want to mount controllers first, after any global middleware. await app.configure(controllers.configureServer); + // Mount our GraphQL routes as well. + await app.configure(graphql.configureServer); + // Render `views/hello.jl` when a user visits the application root. app.get('/', (req, res) => res.render('hello')); diff --git a/pubspec.yaml b/pubspec.yaml index c789831..d5fefbc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -8,13 +8,17 @@ dependencies: angel_auth: ^2.0.0 # Supports stateless authentication via JWT angel_configuration: ^2.0.0 # Loads application configuration, along with support for .env files. angel_framework: ^2.0.0 # The core server library. + angel_graphql: ^1.0.0 # Infrastructure for serving GraphQL. angel_jael: ^2.0.0 # Server-side templating engine angel_production: ^1.0.0 # Production application runner. angel_static: ^2.0.0 # Static file server angel_validate: ^2.0.0 # Allows for validation of input data dev_dependencies: angel_hot: ^2.0.0 # Hot-reloading support. :) + angel_serialize_generator: # Generates serialization code, and more. angel_test: ^2.0.0 # Utilities for testing Angel servers. + build_runner: ^1.0.0 # Runs code builders. + graphql_generator: ^1.0.0 # Generates GraphQL schemas statically. io: ^0.3.2 # For pretty printing. pedantic: ^1.0.0 # Enforces Dart style conventions. test: ^1.0.0 # For unit testing.