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