HATEOAS-first backend framework.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.ts 1.5 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import {
  2. application,
  3. resource,
  4. validation as v,
  5. mediaTypes,
  6. charsets,
  7. } from '../../src';
  8. import {TEXT_SERIALIZER_PAIR} from './serializers';
  9. import {autoIncrement, dataSource} from './data-source';
  10. const Piano = resource(v.object(
  11. {
  12. brand: v.string()
  13. },
  14. v.never()
  15. ))
  16. .name('Piano')
  17. .route('pianos')
  18. .id('id', {
  19. generationStrategy: autoIncrement,
  20. serialize: (id) => id?.toString() ?? '0',
  21. deserialize: (id) => Number.isFinite(Number(id)) ? Number(id) : 0,
  22. schema: v.number(),
  23. })
  24. .canFetchItem()
  25. .canFetchCollection()
  26. .canCreate()
  27. .canEmplace()
  28. .canPatch()
  29. .canDelete();
  30. const User = resource(v.object(
  31. {
  32. firstName: v.string(),
  33. middleName: v.string(),
  34. lastName: v.string(),
  35. bio: v.string(),
  36. birthday: v.datelike()
  37. },
  38. v.never()
  39. ))
  40. .id('id' as const, {
  41. generationStrategy: autoIncrement,
  42. serialize: (id) => id?.toString() ?? '0',
  43. deserialize: (id) => Number.isFinite(Number(id)) ? Number(id) : 0,
  44. schema: v.number(),
  45. })
  46. .name('User')
  47. .route('users')
  48. .fullText('bio');
  49. const app = application({
  50. name: 'piano-service',
  51. })
  52. .mediaType(mediaTypes.applicationJson)
  53. .mediaType(mediaTypes.textJson)
  54. .mediaType(TEXT_SERIALIZER_PAIR)
  55. .charset(charsets.utf8)
  56. .resource(Piano)
  57. .resource(User);
  58. const backend = app.createBackend({
  59. dataSource,
  60. });
  61. const server = backend.createServer({
  62. basePath: '/api'
  63. });
  64. server.listen(3000);
  65. setTimeout(() => {
  66. // Allow user operations after 5 seconds from startup
  67. User
  68. .canFetchItem()
  69. .canFetchCollection()
  70. .canCreate()
  71. .canPatch();
  72. }, 5000);