UNPKG

2.54 kBJavaScriptView Raw
1'use strict';
2
3process.on('exception', function (err) {
4 console.log(err.stack);
5 throw err;
6});
7
8let Gatepost = require('../index');
9let config = require('getconfig');
10let pg = require('pg');
11let SQL = require('sql-template-strings');
12let Joi = require('joi');
13
14Gatepost.setConnection(config.db.uri);
15
16let dbDone, db;
17
18let Author = new Gatepost.Model({
19 name: {
20 validate: Joi.string()
21 },
22 id: {}
23}, {
24 cache: true,
25 name: 'Author'
26});
27
28let Book = new Gatepost.Model({
29 title: {
30 validate: Joi.string()
31 },
32 id: {}
33}, {
34 cache: true,
35 name: 'Book'
36});
37
38Author.fromSQL({
39 name: 'createTable',
40 sql: () => `CREATE TEMP TABLE authors_tmp
41 (id SERIAL PRIMARY KEY, name TEXT)`
42});
43
44Author.fromSQL({
45 name: 'createTable2',
46 sql: () => `CREATE TEMP TABLE books_tmp
47 (id SERIAL PRIMARY KEY, author_id INTEGER REFERENCES authors_tmp(id), title TEXT)`
48});
49
50Author.fromSQL({
51 name: 'dropAuthor',
52 sql: () => `DROP TABLE authors_tmp`
53});
54
55Book.fromSQL({
56 name: 'dropBook',
57 sql: () => `DROP TABLE books_tmp`
58});
59
60Author.fromSQL({
61 name: 'addAuthor',
62 sql: (args, model) => SQL`INSERT INTO authors_tmp (name) VALUES (${model.name}) RETURNING id, name`,
63 instance: true,
64 oneResult: true
65});
66
67module.exports = {
68 setUp: (done) => {
69 done();
70 },
71 tearDown: (done) => {
72 done();
73 },
74 "creating temp tables": (test) => {
75 Author.createTable((err) => {
76 test.ifError(err);
77 Author.createTable2((err) => {
78 test.ifError(err);
79 test.done();
80 });
81 });
82 },
83 "instance: create row": (test) => {
84 let author = Author.create({name: 'Nathan Fritz'});
85 author.addAuthor((err, a2) => {
86 test.ifError(err);
87 test.equals(a2.id, 1);
88 test.equals(a2.name, 'Nathan Fritz');
89 test.done();
90 });
91 },
92 "instance: create row fail": (test) => {
93 let author = Author.create({name: 34});
94 author.addAuthor((err, a2) => {
95 test.ok(err.error !== null);
96 test.done();
97 });
98 },
99 "override factory fail": (test) => {
100 test.throws(() => {
101 Author.fromSQL({
102 name: 'create',
103 sql: () => `POOOOO`
104 });
105 });
106 test.done()
107 },
108 "override instance fail": (test) => {
109 test.throws(() => {
110 Author.fromSQL({
111 name: 'addAuthor',
112 sql: () => `POOOOO`,
113 instance: true
114 });
115 });
116 test.done()
117 },
118 done: (test) => {
119 Book.dropBook().then(() => {
120 return Author.dropAuthor();
121 }).then(() => {
122 pg.end();
123 test.done();
124 })
125 .catch((err) => console.log(err));
126 }
127};