@@ -50,6 +50,7 @@ class Notion
5050 * Notion constructor.
5151 * @param string|null $version
5252 * @param string|null $token
53+ * @throws HandlingException
5354 */
5455 public function __construct (string $ token , string $ version = 'v1 ' )
5556 {
@@ -58,16 +59,20 @@ public function __construct(string $token, string $version = 'v1')
5859 $ this ->validVersions = collect (['v1 ' ]);
5960
6061 $ this ->setVersion ($ version );
62+ $ this ->connect ();
6163
6264 }
6365
6466 /**
6567 *
6668 * @return Notion
69+ * @throws HandlingException
6770 */
6871 private function connect (): Notion
6972 {
70- $ this ->connection = Http::withToken ($ this ->token );
73+ $ this ->connection = Http
74+ ::withHeaders ($ this ->buildRequestHeader ())
75+ ->withToken ($ this ->token );
7176 return $ this ;
7277 }
7378
@@ -89,6 +94,7 @@ public function setVersion(string $version): Notion
8994 * Wrapper function to set version to v1.
9095 *
9196 * @return $this
97+ * @throws HandlingException
9298 */
9399 public function v1 (): Notion
94100 {
@@ -101,11 +107,11 @@ public function v1(): Notion
101107 *
102108 * @param string $token
103109 * @return Notion
110+ * @deprecated for public usage; will be set to private in 0.4.0!
104111 */
105112 public function setToken (string $ token ): Notion
106113 {
107114 $ this ->token = $ token ;
108- $ this ->connect ();
109115 return $ this ;
110116 }
111117
@@ -195,7 +201,37 @@ public function getConnection(): ?PendingRequest
195201 public function checkValidVersion (string $ version ): void
196202 {
197203 if (!$ this ->validVersions ->contains ($ version )) {
198- throw HandlingException::instance ('invalid version for notion-api ' , ['invalidVersion ' => $ version ]);
204+ throw HandlingException::instance ('Invalid version for Notion-API endpoint ' , ['invalidVersion ' => $ version ]);
205+ }
206+ }
207+
208+ /**
209+ * @return string[]
210+ *
211+ * @throws HandlingException
212+ */
213+ private function buildRequestHeader (): array
214+ {
215+ return [
216+ 'Notion-Version ' => $ this ->mapVersionToHeaderVersion ()
217+ ];
218+ }
219+
220+ /**
221+ * Due to the inconsistency of the Notion API requiring a endpoint url
222+ * with v* as well as a dated version in the request header, this method
223+ * maps the given version (e.g. v1) to the version date Notion requires
224+ * in the header (e.g. "2021-05-13").
225+ * @return string
226+ * @throws HandlingException
227+ */
228+ private function mapVersionToHeaderVersion (): string
229+ {
230+ switch ($ this ->version ) {
231+ case 'v1 ' :
232+ return '2021-05-13 ' ;
233+ default :
234+ throw new HandlingException ('Invalid version. ' );
199235 }
200236 }
201237}
0 commit comments