I have a database with some complex relationships mapped and populated with a large amount of data. My requirement is that I need to use this database with Swift-Vapor server.
So that I created a model object (with Fluent framework constructs) similar to the database schema, in order to handle data flows between the vapor server and db.
When it comes the time to link database table(users table) with the model(User model), I found this method, which should implement inside the model class.
static func prepare(_ database: Database) throws {
try database.create("users") { users in
users.id()
users.string("name")
}
}
Since I don't need to define a schema for already existing db, this prepare method just left unimplemented.
The result is that I just can't interact with db, for any operations like userObj.save()
The same thing I achieved with Swift-Perfect Server with the help of the following method implementation inside the model object. This was done with the help MySQLStORM in Perfect.
// Map the model to the database table "user"
override open func table() -> String {
return "user"
}
What I'm looking for is -> Is there any option like this available in Vapor so that I can map model object to a database table?
Got a solution while discussing this issue in Slack community, tried out and working fine.
Solution:
In the model class (say User), the prepare method can be left unimplemented, like
static func prepare(_ database: Database) throws {
}
But should add a static variable entity which will have the table name mapped, like
final class User: Model {
static let entity = "users"
...
}
And finally, we should add the model to the droplets preparations array, like
// Let the User be your model object
drop.preparations.append(User.self)
So that we can use any existing database with complex relations or pre-populated data tables to map with the model object, without constructing tables from model object.
Related
I read in this post that easy tables can have relational database features like join etc for combining tables while querying data. Unfortunately I haven't been able to find much about how to go about doing this.
In my case i have an easy table user and another called subject choice having userid attribute in common and i need to retrieve information in a mobile service app based on info in both of these tables.
How do I go about this?
You can manipulate the easy tables query from the easy api script editor.
You will see a .json and .js file for each "easy table" you created. There will be a commented table.read function with the same signature as my example below. Uncommenting this function and modifying the content allows any kind of custom manipulation server side.
So to do a "Join" you COULD fetch the records from both tables yourself, and then return a "combined" json object.
Here is an example of fetching the data from the storage and deciding when to return:
table.read(function (context) {
var response = context.execute();
response.then(function (records)
{
console.log("Records Fetched: " , records);
// HERE YOU CAN MESS WITH THE DATA
context.res.status(200).send(records);
context.done();
}, function (error)
{
console.log(error);
context.res.status(500).send(error);
context.done();
});
});
According to your description, I followed this tutorial for getting started with the Easy Tables of Azure Mobile App. In my opinion, Easy Tables could provide you with a simple way to add back-end data storage for your mobile app.
We could wrap the operations to the specific table as follows:
public class UserDataService
{
MobileServiceClient mobileService;
IMobileServiceTable<User> userTable;
public void Initialize()
{
mobileService= new MobileServiceClient("http://<your-mobileapp-name>.azurewebsites.net/");
userTable = mobileService.GetTable<User>();
}
public async Task<User> GetUserAsync(string uid)
{
return await this.userTable.LoolupAsync(uid);
}
public async Task AddUserAsync(User user)
{
await this.userTable.InsertAsync(user);
}
}
easy tables can have relational database features like join etc for combining tables while querying data.
As far as I know, you could add a foreign key in a Easy Table for creating your relationships. But you couldn't retrieve data from multiple tables in a single query. For your scenario, you could invoke the methods UserDataService.GetUserAsync and SubjectChoiceDataService.GetByUserIdAsync to aggregate the data as you expected.
I have been facing an issue with Web API 2.2 with Web API OData controller. I am doing a PoC in which I need to display the JSON output from my service with different column names than that of corresponding Model props (DB table columns).
(For ex: 'CompanyName' from Customer table should appear as 'cName' in JSON output of my service.)
I am using DB first approach with Northwind database, created a Model with ADO.NET EF and created a controller using OData EF. (all default no code changes so far)
Now, I have tried to get different names using
1) Data Contract and Data Member -> specifying directly on Model class (yes, auto generated one)
2) JsonProperty -> specifying directly on Model class (yes, auto generated one)
3) DTOs [it works but I don't want use DTOs]
Unfortunately, first 2 approaches are not working for me (not sure what I'm missing here) and DTOs I'm trying to avoid.
I'm stuck on this all my day today, appreciate if you can point me to a right approach.
Note: Instead of OData controller if I use regular Web API controller, all works.
I realize this is old, and I'm not sure which version of OData you are using but the simple answer is, you have to specify all of this information in the model builder.
Here's an example.
var builder = new ODataConventionModelBuilder();
var entity = builder.EntitySet<Model>("models").EntityType;
entity.Name = "model";
entity.Property(p => p.Id).Name = "id";
entity.Property(p => p.Name).Name = "name";
entity.Property(p => p.Description).Name = "description";
Good luck!
I have a dynamic object I need to persist whose definition and values change according to different users. You can think of them as dynamic forms which admin first defines and later is filled up by different users.
I do not have any alternative than MySQL for my project so schema-less db is out of question.
I could have done it using normal relational model storing fields and there values on multiple table but it felt too clumsy. So I decided to store those dynamic objects as JSON on MySQL table.
Is this a good approach ? If not can you suggest any proper alternatives?
In any case I am having problem retrieving the object as JSON from the database using Grails. This is my sample class where definition is the field where JSON needs to be stored.
String subJobType
String definition
static constraints = {
definition nullable: false
}
static mapping = {
definition sqlType: 'MEDIUMTEXT',type: 'text'
}
I can only retrieve the definition field as a string but want to return a object instead.
I could first fetch all the objects and then convert all definition field of each object to JSON but that doesn't sound a good idea.
I am making a simple REST API in front of a NoSQL database that stores records as documents similar to JSON (but not exactly the same). Each record has some fields, including id for the database, and also including some derived fields, like dateCreated.
Any time I GET anything, I want to return the objects with all the fields.
// GET /users returns an array of these in JSON
// [{id:"xxx", name:"Bobby", dateCreated:"YYYY-MM-DD"]
data User = User { id :: String, name :: String, dateCreated :: XXX }
But any time I POST or PUT anything, they client should send an object with the id field and any derived fields missing. The database is responsible to create the id when I save it, and I would create some derived fields
// POST /users would need you to post only the name.
// {name:"Henry"}
data PartialUser = PartialUser { name :: String }
If resource represents objects of type User, what should I call the thing client is sending to me? Would you make all the derived fields Maybe values? Or would you create a second object called PostedUser or something?
It can be many things:
a request body
the representation of the intended resource state of the client
a command DTO which you can send to the domain logic in order to process it by CQRS
I would make it CreateUser command, but if you don't want to use CQRS and DDD, then you would probably call it as PartialUserRepresentation, or you don't create a data structure, just use the properties to create a new User entity. Ofc. if you use entities.
So I would say it depends on the architecture of your system.
I have 2 classes named User.groovy and Employee.groovy and I used MYSQL to save the data. What I want is to create a new User account and save it to the User table and also save some of the data to Employee table. How can I do this? I've tried extending the user to Employee but the data only saved to User and not to Employee. But If I don't extend the User, the data is only saved to Employee. What should I do so that the data simultaneously saves to two database tables at the same time? Please help me.
Actually have this in my class user:
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
.....}
and employee:
class Employee {
String name
String email
String jobDesc
....}
So what should I do next? I'm sorry for this, I'm still starting to learn grails.
Grails paradigm (as far as scaffolding is concerned) is one form - one object. As long as you stick to this paradigm, you get all the goodies, such as input validation and error reporting for free (you may also consider using the Fields plugin here http://grails.org/plugin/fields).
However, sometimes you need to collect info and create two or more objects through single form. Usually this happens when you need to initiate new subscription and collect info for both subscription details (say, Subscription entity) and user info (User entity). This is where command objects come to rescue.
http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects
So, instead of expanding/bending SubscriptionController or UserController (or UserController and EmployeeController, as per your example), you create SignUpController, which handles SignUpCommand object. The SignUpCommand object is not intended to be saved, it is used as a backing object for the SignUpController.create form. When it validates, you use the signUpCommand object data to initialize 2 domain objects (that is Subscription and User) and save these objects individually within the same transaction.
You can either delegate the save operation to a service say,
if (signUpCmd.validate()) {
SignUpService.save(signUpCmd))
}
or create and save both objects right on the spot within controller
if (signUpCmd.validate()) {
Subscription subscription = new Subscription(plan: signUpCmd.plan, ...)
subscription.save()
User user = new User(username: signUpCmd.username, ...)
user.save()
}
it is mostly matter of taste and style.
Instead of calling save() directly to your user instance, call a service class that saves both the user and the employee in one atomic operation. Like, for instance:
class UserController {
/*Injection of your service in the controller class*/
def userService
And then in the save action in this same controller:
userService.save(user) // userService.save(params)
And inside this service method you will extract the data (user or params, whatever floats your boat) you want to save in a different table as long as the usual user object.