HATEOAS-first backend framework.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

77 rader
1.5 KiB

  1. import {
  2. application,
  3. resource,
  4. valibot as v,
  5. serializers,
  6. encodings,
  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. .id('id', {
  18. generationStrategy: autoIncrement,
  19. serialize: (id) => id?.toString() ?? '0',
  20. deserialize: (id) => Number.isFinite(Number(id)) ? Number(id) : 0,
  21. schema: v.number(),
  22. })
  23. .canFetchItem()
  24. .canFetchCollection()
  25. .canCreate()
  26. .canEmplace()
  27. .canPatch()
  28. .canDelete();
  29. const User = resource(v.object(
  30. {
  31. firstName: v.string(),
  32. middleName: v.string(),
  33. lastName: v.string(),
  34. bio: v.string(),
  35. birthday: v.datelike()
  36. },
  37. v.never()
  38. ))
  39. .name('User')
  40. .fullText('bio')
  41. .id('id', {
  42. generationStrategy: autoIncrement,
  43. serialize: (id) => id?.toString() ?? '0',
  44. deserialize: (id) => Number.isFinite(Number(id)) ? Number(id) : 0,
  45. schema: v.number(),
  46. });
  47. const app = application({
  48. name: 'piano-service',
  49. dataSource,
  50. })
  51. .contentType('application/json', serializers.applicationJson)
  52. .contentType('text/json', serializers.textJson)
  53. .contentType('text/plain', TEXT_SERIALIZER_PAIR)
  54. .encoding('utf-8', encodings.utf8)
  55. .resource(Piano)
  56. .resource(User);
  57. const backend = app.createBackend();
  58. const server = backend.createServer({
  59. baseUrl: '/api'
  60. });
  61. server.listen(3000);
  62. setTimeout(() => {
  63. // Allow user operations after 5 seconds from startup
  64. User
  65. .canFetchItem()
  66. .canFetchCollection()
  67. .canCreate()
  68. .canPatch();
  69. }, 5000);