d-idioms
d-idioms copied to clipboard
CRTP
CRTP by Adam:
import arsd.cgi;
import arsd.postgres;
class Employee : RestObject!(Employee) {
// implement the data members as plain old data
// the annotation is actually for my database helpers
// rather than the web code but eh it works nicely together.
@DbSave {
int id;
string name;
string title;
int salary;
}
mixin DatabaseRestObject!(() => new PostgreSql("dbname=test"));
}
// a collection can be auto-generated, but it will probably need some custom code
// to load, so we can subclass that too. It is templated on the type of the collection..
class Employees : CollectionOf!(Employee) {
// and the one method you will want to implement is index.
// later, it will support pagination, searching, and sorting, but
// all I have implemented so far is the basic listing.
override IndexResult index() {
IndexResult ir;
/*
ir.fields.add("id");
ir.fields.add("name");
ir.fields.add("title");
*/
auto db = new PostgreSql("dbname=test");
foreach(row; db.query("SELECT id, name, title, salary FROM employees LIMIT 30")) {
// it is expected to return the object in question with data
// members set. It shouldn't expect ALL members set though, but I haven't
// fully implemented that detail.
auto e = new Employee();
rowToObject(row, e);
ir.results ~= e;
}
return ir;
}
}
mixin DispatcherMain!(
"/employees".serveRestObject!Employees,
"/".serveRedirect("employees"),
);