1 /// This module provides Date serialization with an extra added magic value to serialize the current date at serialization time.
2 module mongoschema.date;
3 
4 import std.datetime.systime;
5 
6 import vibe.data.bson;
7 
8 /// Class serializing to a bson date containing a special `now` value that gets translated to the current time when converting to bson.
9 final struct SchemaDate
10 {
11 public @safe:
12 	///
13 	this(BsonDate date)
14 	{
15 		_time = date.value;
16 	}
17 
18 	///
19 	this(long time)
20 	{
21 		_time = time;
22 	}
23 
24 	///
25 	@property auto time() const
26 	{
27 		return _time;
28 	}
29 
30 	///
31 	static Bson toBson(SchemaDate date)
32 	{
33 		if (date._time == -1)
34 		{
35 			return Bson(BsonDate.fromStdTime(Clock.currStdTime()));
36 		}
37 		else
38 		{
39 			return Bson(BsonDate(date._time));
40 		}
41 	}
42 
43 	///
44 	static SchemaDate fromBson(Bson bson)
45 	{
46 		return SchemaDate(bson.get!BsonDate.value);
47 	}
48 
49 	///
50 	static SchemaDate fromSysTime(SysTime stime)
51 	{
52 		return SchemaDate(BsonDate(stime).value);
53 	}
54 
55 	/// Magic value setting the date to the current time stamp when serializing.
56 	static SchemaDate now()
57 	{
58 		return SchemaDate(-1);
59 	}
60 
61 	/// Converts this SchemaDate to a std.datetime.SysTime object.
62 	SysTime toSysTime() const
63 	{
64 		if (_time == -1)
65 			return Clock.currTime;
66 		return BsonDate(_time).toSysTime();
67 	}
68 
69 	/// Converts this SchemaDate to a vibed BsonDate object.
70 	BsonDate toBsonDate() const
71 	{
72 		return BsonDate(_time);
73 	}
74 
75 	///
76 	string toISOExtString() const
77 	{
78 		return toSysTime.toISOExtString;
79 	}
80 
81 	///
82 	static SchemaDate fromISOExtString(S)(in S s) if (isSomeString!S)
83 	{
84 		return SchemaDate.fromSysTime(SysTime.fromISOExtString(s));
85 	}
86 
87 private:
88 	long _time;
89 }
90 
91 static assert (isISOExtStringSerializable!SchemaDate);